java - 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;
}
解决方案
事实上,你必须断言更多。
要检查该方法的实际行为,您确实应该从返回的列表中断言:
- 该列表具有预期的大小
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
因为不期望元素的顺序:数字是随机的。
作为旁注,您的实施效率不高。
使用大范围和接近范围大小的请求大小,您可以循环比需要的多得多。
推荐阅读
- c++ - Windows 版本的 MPIR 内存损坏错误
- galaxy - 在远程机器中找不到引导服务
- javascript - 在 Javascript 中构造对象数组的索引顺序始终是 0,1,...n
- javascript - 为什么 JSON.parse 在异步单元测试中导致问题,但在控制台中却没有?
- loops - 有没有办法在 terraform 的 for / for_each 循环中获取索引?
- python - 在 MacOS 上安装 pip 包失败,出现“错误:命令‘gcc’失败,退出状态为 1”
- java - Blazor WASM / Java:选择文本并模拟 KeyPress
- node.js - axios 获取请求返回未定义对象
- python - 提取两个列表项的任何排列之间的所有子字符串
- javascript - Nodejs 使用未定义的 Json 处理 Api