我想测试一个比较对象中两个双精度值的compareTo 方法。
我想测试的方法:
public int compareTo(Participant other) {
return Double.compare(this.handicap, other.handicap);
}
Run Code Online (Sandbox Code Playgroud)
此方法比较让分双倍值(例如从 -1.0 到 5)。物体:
public Participant(String naam, double handicap, String thuisbaan) {
this.naam = naam;
this.handicap = handicap;
this.thuisbaan = thuisbaan;
}
Run Code Online (Sandbox Code Playgroud)
我想为此创建一个测试方法,但不知道如何......
你可以像这样简单地做到这一点。
@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");
}
Run Code Online (Sandbox Code Playgroud)
由于您的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 */
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3618 次 |
| 最近记录: |