只有在抛出6个IllegalArgumentExceptions时才需要传递JUnit

时间:2014-11-03 18:39:34

标签: java exception junit illegalargumentexception

每个新语句M#().multiply(-1)都会引发IllegalArgumentException。现在如果抛出至少1个异常,则传递。如果每个语句new M#().multiply(-1)都抛出异常,我只需要传递它。

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

@Test
public void test(){

    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Integers must be positive");

    new M1().multiply(-1);
    new M2().multiply(-1);
    new M3().multiply(-1);
    new M4().multiply(-1);
    new M5().multiply(-1);
    new M6().multiply(-1);

}

我已经在这方面工作太久了,请帮忙。

1 个答案:

答案 0 :(得分:2)

首先,我不认为单元测试应该这样做。您可以简单地创建6个测试,每个测试创建一个不同的类对象并期待异常。

然而,对于这种情况,你可以抓住IllegalArgumentException并计算它们发生的次数:

int exceptionCount = 0;
try {
    new M1().multiply(-1);
} catch(IllegalArgumentException ex) {
    exceptionCount++;
}
try {
    new M2().multiply(-1);
} catch(IllegalArgumentException ex) {
    exceptionCount++;
}
...
Assert.assertEquals(exceptionCount, 6);