JUnit异常测试失败(意外)

时间:2013-09-07 14:18:32

标签: java exception testing junit

我正在尝试运行JUnit测试来测试会抛出异常的方法。但是,测试失败了,我不知道它失败的原因。抛出异常的方法是:calcultor.setN();.我做了两个版本的测试,即使它们应该通过,它们都会失败。

@Rule
public ExpectedException exception = ExpectedException.none();    

@Test
public void testSetNZero() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Het aantal CPU's is minder dan 1");
    Amdahl calculator = new Amdahl();
    calculator.setN(0);
    fail("Exception not thrown");
}

@Test (expected = IllegalArgumentException.class)
    public void testSetNZero() {
    Amdahl calculator = new Amdahl();
    calculator.setN(0);
}

Amdahl班:

public class Amdahl 
{
    private int N;

    public void setN (int n) {
    if(n < 1) throw new IllegalArgumentException ("Het aantal CPU's is minder dan 1");
    this.N = n;
    }
}

2 个答案:

答案 0 :(得分:1)

testSetNZero失败是因为:

@Test (expected = IllegalArgumentException.class)
public void testSetNZero() {

@Rule
public ExpectedException exception = ExpectedException.none();

相互矛盾并定义一个总是会失败的测试(它必须抛出异常而不是为了通过)。使用ExpectedException @Test(expected = ...)

答案 1 :(得分:0)

每当我预料到异常时,我就通过使用try-catch块解决了我的问题。如果没有异常或错误的异常,则测试失败。

@Test
public void testSetNZero() {
    Amdahl calculator = new Amdahl();
    try{
        calculator.setN(0);
        fail();
    } catch(IllegalArgumentException e){}
}