我想测试一个比较对象中两个 double 值的 compareTo 方法。
我要测试的方法:
public int compareTo(Participant other) {
return Double.compare(this.handicap, other.handicap);
}
此方法比较双倍让分值(例如从 -1.0 到 5)。 对象:
public Participant(String naam, double handicap, String thuisbaan) {
this.naam = naam;
this.handicap = handicap;
this.thuisbaan = thuisbaan;
}
我想为此创建一个测试方法,但不知道如何...
最佳答案
你可以这么简单地做到这一点。
@Test
void testCompareTo() {
// given:
Participant james = new Participant("James", 12.0, "Random1");
Participant jane = new Participant("Jane", 212.0, "Random2");
// when: then:
Assertions.assertEquals(-1, james.compareTo(jane), "Should James be smaller than Jane");
// given:
james = new Participant("James", 12.0, "Random1");
jane = new Participant("Jane", 12.0, "Random2");
// when: then:
Assertions.assertEquals(0, james.compareTo(jane), "Should James and Jane be equal");
// given:
james = new Participant("James", 212.0, "Random1");
jane = new Participant("Jane", 12.0, "Random2");
// when: then:
Assertions.assertEquals(1, james.compareTo(jane), "Should James be bigger than Jane");
}
因为你的 compareTo
方法是一个非常简单的方法,你实际上不需要测试它,我会说,因为它只是 Double#compareTo
完成了所有工作。但是,如果您在那里引入一些逻辑,那么它就会有意义。总体而言,您可以遵循以下模式:
// given:
/* initialize all your objects here, including mocks, spies, etc. */
// when:
/* the actual method invocation happens here */
// then:
/* assert the results, verify mocks */
关于java - 当 arraylist 包含对象时,如何使用 Junit/Java 测试 compareTo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62349054/