尝试测试以下方法,有 3 个场景。 如果两个对象相等,则返回 zer0,如果“this”大于另一个对象,则返回正数,否则返回负数。
我是否为 3 个案例编写了 3 个不同的测试?或者我可以在一个测试方法中完成这一切吗? 谢谢
public int compareTo(Vehicle v){
if(this.getLengthInFeet() == ((Boat)v).getLengthInFeet()){
return 0;
}else if(this.getLengthInFeet() > ((Boat)v).getLengthInFeet()){
return 10;
}else{
return -10;
}
}
最佳答案
看看@Parameterized .这将为您提供具有多个数据点的测试方法。以下是示例(未经测试):
@RunWith(Parameterized.class)
public class XxxTest {
@Parameters
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 0, 10, 10 },
{ -10, 10, 20 },
});
}
private final int expected;
private final int thisFeet;
private final int vFeet;
public XxxTest(int expected, int thisFeet, int vFeet) {
this.expected = expected;
this.thisFeet = thisFeet;
this.vFeet = vFeet;
}
@Test
public void test() {
Vehicle vThis = new Vehicle(thisFeet);
Vehicle vThat = new Vehicle(vFeet);
assertEquals(expected, vThis.compareTo(vThat));
}
}
关于java - 我如何对 toCompare() 方法进行单元测试,比较 2 个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18107440/