JUnit测试返回null和false

时间:2014-01-29 23:23:21

标签: java junit

所以我在JUnit中练习参数化测试。我创建了这个类:

public class Operation {

    public Operation() {

    }

    public int add(int value, int num) {
        int ans = value + num;
        return ans;
    }

    public int subtract(int value, int num) {
        int ans = value - num;
        return ans;
    }
}

没什么特别的,只是一些方法来运行一些测试。

我在这里有这个测试课:

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class OperationTest {

    private int value;
    private int num;

    public OperationTest(int expected, int value, int num) {
        this.value = value;
        this.num = num;
    }

    @Parameterized.Parameters
    public static Collection primeNumbers() {
        return Arrays.asList(new Object[][] {
                { 4, 2, 2 },
                { 66, 6, 60 },
                { 20, 19, 1 },
                { 82, 22, 50 },
                { 103, 23, 80 }
        });
    }

    @Test
    public void test() {
        Operation o = new Operation();
        assertTrue(value == o.add(value, num));
    }

}

最后我有一个班来运行我的测试:

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
    public static void main(String[] args) {
        Result result = JUnitCore.runClasses(OperationTest.class);
        for(Failure f : result.getFailures()) {
            System.out.println(f.toString());
        }

        System.out.println(result.wasSuccessful());
    }
}

当我运行它时,输出为:

test[0](OperationTest): null
test[1](OperationTest): null
test[2](OperationTest): null
test[3](OperationTest): null
test[4](OperationTest): null
false

我期待所有这些都是真的,因为{4,2,2}意味着期望4和2中的4作为参数提供给Operation类中的add方法...我猜这个可能不是正确的方法......

我很感激你的见解。

2 个答案:

答案 0 :(得分:2)

你没有在任何地方使用expected - 甚至没有让它成为班级状态的一部分。你的断言在这里:

assertTrue(value == o.add(value, num));

...没有断言你想要它。只有在num为0时它才会起作用。仔细看看。

你应该:

// final is optional here, of course - but that's what I'd do, anyway :)
private final int expected;
private final int value;
private final int num;

public OperationTest(int expected, int value, int num) {
    this.expected = expected;
    this.value = value;
    this.num = num;
}

然后:

assertTrue(expected == o.add(value, num));

或更好(更清晰的诊断):

assertEquals(expected, o.add(value, num));

答案 1 :(得分:2)

考虑到value == value + numbervalue为零(我们可以通过查看您的测试数字看到),number如何才能成真?你在逻辑上显然错过了一些简单的东西。我想你需要一个表达预期结果的第三个参数,所以你可以这样做:

expected == o.add(value, number);
相关问题