问题描述:

Each statement new M#().multiply(-1) throws an IllegalArgumentException. Right now This passes if at least 1 exception is thrown. I need this to only pass if every single statement new M#().multiply(-1) throws an exception.

@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);

}

I've been working on this for way too long now, please help.

网友答案:

First, I don't think a unit test should do this. You can simply create 6 tests, each creating a different class object and expecting an exception.

Yet still, for this situation, you can catch the IllegalArgumentExceptions and count how many times they occur:

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);
相关阅读:
Top