5 ms·
That's quite an old fashioned way of testing exceptions, TestNG has allowed you to do the following since 2005: @Test(expectedExceptions = FooBarException.
by laureny 13y ago
That's quite an old fashioned way of testing exceptions, TestNG has allowed you to do the following since 2005:
@Test(expectedExceptions = FooBarException.class)
public void test() {
thisShouldThrow();
}
If the method doesn't throw or throws the wrong kind of exception, this test will fail.
- Nitramp 13y agoThat has the problem of separating the statement that is supposed to throw and then thrown exception. E.g. a slightly more complicated test case: @Test(expectedExceptions = FooException.class) public void test() { firstDoThis(); thenThat(); thenSomeMore(); thisShouldThrow(); } Now you're only asserting that any of these statements throw, anywhere in the code under test. That's significantly weaker and I've seen it mask real problems in code. I think using plain try something/fail/catch is clearer, or using Closures and an assertThrows if your language supports it.
- Nilzor 13y agoYou should probably think of splitting up your test case if it's this complicated.
- pygy_ 13y agoIn that case, you first write a test case ensuring that the first three statements won't throw.
- laureny 13y agoYou can always revert to the old try/catch/fail if you need to test something more complex (e.g. testing the message of the exception) but most of exception tests fall in the simple case shown above.