How can I test a class that returns the Fibonacci series? I used an iterator for this code. The FibonacciIteratorTest class is below.
public class FibonacciIterator implements Iterator<Integer>, Iterable<Integer>{
private int num1;
private int num2;
private int num3;
private int count;
private int to;
public FibonacciIterator(int to){
this.num1 = 0;
this.num2 = 1;
this.to = to;
this.count = -1;
}
public static Iterable<Integer> to(int num){
return new FibonacciIterator(num);
}
@Override
public Iterator<Integer> iterator(){
return this;
}
@Override
public boolean hasNext(){
if(count < to){
count++;
return true;
}
return false;
}
@Override
public Integer next(){
if(count < 2){
return count;
}
num3 = num1 + num2;
num1=num2;
num2=num3;
return num3;
}
}
Instead of 55, the expected values should be 0 1 1 2 3 5 8 13 21 34 55.
class FibonacciIteratorTest {
@Test
void shouldReturnFibonacciNumbers(){
FibonacciIterator fibonacciNumbers= new FibonacciIterator();
assertEquals(55,fibonacciNumbers.to());
}
}
Considering your fibonacciNumbers.to method returning int [] then you might want to use assertArrayEquals:
int arr[]={0,1,1,2,3,5,8,13,21,34};
assertArrayEquals(arr, fibonacciNumbers.to(10));
If your method fibonacciNumbers.to() returns other than int array, then please tell us, so that answer can be changed accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With