Test Smell: Unnecessary Test Code
Learn about exceptions in Search methods and how to prevent them.
We'll cover the following
Expect the exceptions
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.
If our tests expect an exception to be thrown because we’ve explicitly designed the test to prepare for them, then we can simply let the exceptions fly.
Don’t worry, JUnit traps any exceptions that explode out of our 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 adds no additional value.
try/catch
removal
In the following code, remove the try/catch
block and modify the signature of testSearch()
to indicate that it can throw an IOException
.
- Remove the
try
statement from line 14. - Replace line 13 with:
public void testSearch() throws IOException {
- Remove the
catch
block from lines 46-49. - Now run the test.
Get hands-on with 1400+ tech skills courses.