mercredi 20 février 2019

Not sure my why JUnit test is coming back successful, when it's intentionally meant to be a failure

I'm brand new to JUnit so I'm sorry if what I'm asking is too simple. I've searched online and I believe I'm doing everything correctly when it comes to the assertTrue() method. Yet when I run this test, it comes back that it passed, when it is intentionally meant to fail. Let me know if I'm doing anything wrong. I'm currently using Intellij IDEA and JUnit4. Here's my main class:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PrimeNumbers implements Iterable<Integer> {
    private List<Integer> primes = new ArrayList<Integer>();

    /*
     * creates a list of n prime numbers
     *
     * @param n - the number of primes to compute silently treats negative
     * arguments as zero
     */
    public void computePrimes(int n) {
        int count = 1; // count of primes
        int number = 2; // number tested for primeness
        boolean isPrime; // is this number a prime

        while (count <= n) {
            isPrime = true;
            for (int divisor = 2; divisor <= number / 2; divisor++) {
                if (number % divisor == 0) {
                    isPrime = false;
                    break; // for loop
                }
            }
            if (isPrime && (number % 10 != 9)) { // THIS IS THE FAULT!!!
                primes.add(number);
                count++;
            }
            number++;
        }
    }

    @Override
    public Iterator<Integer> iterator() {
        return primes.iterator();
    }

    @Override
    public String toString() {
        return primes.toString();
    }

}

and here's my test class:

import org.junit.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.*;

public class PrimeNumbersTest {

    @Test
    public void test(){

        //instantiate prime object, create primes list, and iterator
        PrimeNumbers prime = new PrimeNumbers();
        List<Integer> primes = new ArrayList<Integer>();
        Iterator<Integer> primeIterator = primes.iterator();

        //array holding 19 so I can compare the objects
        int[] primeArray = new int[]{2,3,5,7,11,13,17,19};
        int i = 0;
        int n = 8;

        //call the method
        prime.computePrimes(n);

        //loop to iterate through the list and then check last item if it is equal to 19
        while(primeIterator.hasNext()){
            if(!(primeIterator.equals(primeArray[i]))) {
                assertTrue("incorrect", primeIterator.equals(primeArray[i]));
            }
            i++;
            primeIterator.next();
        }
    }
}

Thanks guys!

Aucun commentaire:

Enregistrer un commentaire