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());
}
}