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 - Intellij 中 Checkstyle 扫描期间出现异常

Java - 理解递归

python - 项目文件夹中的 __init__.py 中断了 Nose 测试

eclipse - 如何通过 eclipse 在 JUnit 测试中使用 persistence.xml 和 hibernate.cfg.xml?

java - Ant/JUnit - 如何断言包依赖项/非依赖项?

java - 以linux风格定义的路径是一个最终变量。 windows下打不开路径

testing - 如何找到循环的固定点以及我们为什么需要这个?

javascript - 实时可访问性检查器

eclipse - 在Eclipse中运行JUnit Test将打开控制台面板

java - 删除不需要的参数