Test Smell: Unnecessary Test Code

The test code that comprises testSearch() doesn’t expect any exceptions to be thrown. It contains a number of assertions against positive facts. If the test code throws an exception, a try/catch block catches it, spews a stack trace onto System.out, and explicitly fails the test. In other words, exceptions are unexpected by this test method.

Unless your tests expect an exception to be thrown—because you’ve explicitly designed the test to set the stage for throwing an exception—you can simply let the exceptions fly. Don’t worry, JUnit traps any exceptions that explode out of your test. JUnit marks a test that throws an exception as an error and displays the stack trace in its output. The explicit try/catch block ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.