简体   繁体   English

Java:使用迭代器测试方法

[英]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,3,5,7,11]并搜索7,则应返回3”
  2. "if I have the list [2,3,5,7,11] and I search for 6, it should return -1" “如果我有列表[2,3,5,7,11]并搜索6,它应该返回-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. 如果您的算法完全不依赖未排序/降序排序,则不要测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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