gpt4 book ai didi

java - 列表排序实现的单元测试?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:09:14 25 4
gpt4 key购买 nike

我目前正在编写一个单元测试,用于检查某个方法是否正确地对列表进行排序。

排序方法覆盖了compare来自类的方法 Comparator并使用 Collections.sort() 对列表进行排序.

这可能不是技术问题,但我正在寻找一种方法来使用 JUnit 的断言来检查列表是否正确排序...

列表按其持有的类型的内部参数排序,我称之为 id .因此,当列表包含 3 个 ID 为:3、1、2 的项目时 - 它应将它们排序为 1、2、3。

Long expected1 = listOfObjects.get(0).getId()
Long expected2 = listOfObjects.get(1).getId()
Long expected3 = listOfObjects.get(2).getId()

然后在那些 Long 对象上使用断言看起来既不干净也不聪明。我正在寻找如何干净利落地测试这种情况的想法,但我没有想法......

最佳答案

IMO,你应该只对你写的 compare 方法进行单元测试。 Collections.sort() 已经过严格测试!

只需进行一个简单的最终测试,以确保 Collections.sort() 被您编写的方法正确调用:

private final MyComparator comparator = new MyComparator();

@Test
public greaterTest() {
MyObject o1 = new MyObject(2);
MyObject o2 = new MyObject(1);
int c = comparator.compare(o1, o2);
// assert that c is > 0
}

@Test
public lowerTest() {
MyObject o1 = new MyObject(1);
MyObject o2 = new MyObject(2);
int c = comparator.compare(o1, o2);
// assert that c is < 0
}

@Test
public equalTest() {
MyObject o1 = new MyObject(2);
MyObject o2 = new MyObject(2);
int c = comparator.compare(o1, o2);
// assert that c is == 0
}

@Test
public sortTest() {
List<MyObject> os = // ...
// call to the function that makes the call to Collections.sort
List<MyObject> expected = // sorted version of os
// assert that the sorted list is equal to the expected one
}

关于java - 列表排序实现的单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com