首页 > 解决方案 > JUnit 测试 ArrayList 元素不重复

问题描述

使用此方法,该方法使用来自被调用方法 getRandomInt 的随机值生成 ArrayList。我会断言什么来创建一个测试 ArrayList 不包含重复项的测试方法?

public static int getRandom(int min, int max) {

    return random.nextInt((max - min) + 1) + min;
}

public static ArrayList<Integer> getRandomIntegers(int size, int min, int max) {

    ArrayList<Integer> number = new ArrayList<Integer>();

    while (number.size() < size) {
        int random = getRandom(min, max);

        if(!number.contains(random)) {
            number.add(random);
        }
    }

    return number;
} 

标签: javajunit

解决方案


事实上,你必须断言更多。
要检查该方法的实际行为,您确实应该从返回的列表中断言:

  • 该列表具有预期的大小

Assert.assertEquals(size, list.size());

  • 该列表不包含 dup

Assert.assertEquals(new HashSet<Long>(list).size(), actualList.size());

  • 列表元素在传递给的 min-max 范围内。

for (long v : list){ Assert.assertTrue(v " + " is not in the expected range", v >= min && v <= max); }

Set正如 M. le Rutte 强调的那样,我还认为方法 API 返回 a而不是更有意义,List因为不期望元素的顺序:数字是随机的。

作为旁注,您的实施效率不高。
使用大范围和接近范围大小的请求大小,您可以循环比需要的多得多。


推荐阅读