java - 我如何对 toCompare() 方法进行单元测试,比较 2 个对象?

标签 java testing junit

尝试测试以下方法,有 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/

相关文章:

java - 如何在静态类中加载字体并用作 JAR

java - Java流将字符串列表排序为数字问题

testing - 我可以覆盖 RESTClient 默认 "HttpResponseException"对 >399 返回码的响应吗?

java - 编写 JUnit 测试用例请求调度程序时出错

java - 如何验证 lambda 函数 Mockito

java - 从迭代器创建的 CompletableFuture 流不会延迟计算

java - Android sdk 18 TextView 重力不能垂直工作

testing - 自动化测试无济于事的场景

java - Arquillian glassfish-managed 测试 Absent Code 属性错误

java - 在java中的单元测试的服务类中注入(inject)不断增长的依赖关系的最佳方法是什么