Re:Unit testing best practices
by beothorn on Tuesday November 06, 2012 @07:24AM
(#4748057)
"Create unit tests that target exceptions" , @Test(expected=NullPointerException.class)
Don't do this, any point of your test can throw this exception. A try/catch with an assert avoids false negatives and documents where you were expecting the exception to be thrown.
edit: typo
[ Parent
| on HN ]
I'd suggest that if you need to document where is throwing the exception, you're doing too much work in the test.
Setup code should be pretty simple and stable, so should very rarely suddenly start throwing new exceptions.
If you need to pinpoint which bit of code under test threw the exception, you're probably testing too much in one test.
Of course, the advice changes when you're using a unit testing framework as a runner for integration tests.
One can precisely handle exceptions with JUnit's ExpectedException:
http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rule...
This is more compact and declarative than the usual
try {
...;
fail();
} catch (...) {
// expected
}
Re:Unit testing best practices
by benjiweber on Tuesday November 06, 2012 @09:15AM
(#4748437)
I think it's just a poor example to illustrate the point.
Firstly this is most useful when it's @Test(expected=SomeDomainSpecificException.class) NPEs can be thrown by anything.
Secondly, if you're following the other advice and have tests that test only one thing and assert only one thing then there should be only one line that can throw an Exception.