Camila Camila - 6 months ago 70
Java Question

Java: Testing a method with iterator

My testing method is failing. I'm not sure what to place in iterators place. Currently is null. How to test this when there is iterator?

Here is full main class which works, all it does is searching through array and returns index of the given number:

public class Main {
public static void main(String[] args) {

final List<Integer> numbers = Arrays.asList(3, 4, 6, 1, 9);
final Integer x = Integer.valueOf(1);
System.out.println(findSame(numbers.iterator(), x, 0));
public static final int findSame(Iterator<Integer> iterator, Integer x, int idx) {
if (!iterator.hasNext()) {
return -1;

if ( {
return idx;
} else {
return findSame(iterator, x, idx+1);

Here is my testing trial method, which is not functional.

public void searchNumReturnsIndex1(){
Main instance = new Main();


Iterator<Integer> iterator = null;

int x = 6;

int expResult = 2;
int result = Main.findSame(iterator, x, 2);

assertEquals(expResult, result);

Answer Source

Your test should be testing something. Like,

  1. "if I have the list [2,3,5,7,11] and I search for 7, it should return 3"
  2. "if I have the list [2,3,5,7,11] and I search for 6, it should return -1"

Once you've decided what your tests should be, they should be short, simple things that test exactly that one case.

public void searchFor7InShortListOfPrimes() {
    List<Integer> numbers = Arrays.asList(2, 3, 5, 7, 11);
    assertEquals(3, Main.findSame(numbers.iterator(), 7, 0));  

public void searchFor6InShortListOfPrimes() {
    List<Integer> numbers = Arrays.asList(2, 3, 5, 7, 11);
    assertEquals(-1, Main.findSame(numbers.iterator(), 6, 0));  

But the tests should cover all possibilities. Like, what if the list is in descending order, or is not sorted at all. Whatever is appropriate for your method; don't test unsorted/descending sorted if your algorithm doesn't depend on that at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download