簡體   English   中英

Java:使用迭代器測試方法

[英]Java: Testing a method with iterator

我的測試方法失敗。 我不確定在迭代器中放置什么。 當前為空。 有迭代器時如何測試?

這是完整的主類,它的工作原理是,它通過數組搜索並返回給定數字的索引:

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

這是我的測試試用方法,不起作用。

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

您的測試應該正在測試某些東西。 喜歡,

  1. “如果我有列表[2,3,5,7,11]並搜索7,則應返回3”
  2. “如果我有列表[2,3,5,7,11]並搜索6,它應該返回-1”

確定了測試內容后,它們應該是簡短,簡單的事情,可以准確地測試一種情況。

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

但是測試應該涵蓋所有可能性。 就像,如果列表是降序排列,或者根本沒有排序怎么辦。 任何適合您的方法; 如果您的算法完全不依賴未排序/降序排序,則不要測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM