4 ms·
"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/ca
by beothorn 14y ago
"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
- ajanuary 14y agoI'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.
- benjiweber 14y agoI 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.
- gaul 14y agoOne can precisely handle exceptions with JUnit's ExpectedException: http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rules/ExpectedException.html http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rule... This is more compact and declarative than the usual try { ...; fail(); } catch (...) { // expected }