0

我正在尝试运行 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);
}

阿姆达尔类:

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;
    }
}
4

2 回答 2

1

testSetNZero失败是因为:

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

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

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

于 2013-09-07T16:00:11.800 回答
0

每当我预期出现异常时,我都通过使用 try-catch 块解决了我的问题。如果没有异常或存在错误异常,则测试失败。

@Test
public void testSetNZero() {
    Amdahl calculator = new Amdahl();
    try{
        calculator.setN(0);
        fail();
    } catch(IllegalArgumentException e){}
}
于 2014-07-07T07:41:59.923 回答