每个新语句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);
}
我已经在这方面工作太久了,请帮忙。
答案 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);