简体   繁体   中英

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 (iterator.next().equals(x)) {
        return idx;
    } else {
        return findSame(iterator, x, idx+1);
    }
    }
}

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

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

    System.out.println("Index");

    Iterator<Integer> iterator = null;

    int x = 6;

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

    assertEquals(expResult, result);  
    }

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.

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

@Test
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM