Test Smell: Irrelevant Details
Learn how to remove irrelevant details by using the @After and @Before helper methods.
We'll cover the following
Distractions
Although we want to turn off logging when tests run, the code to do so is a distraction to understanding the essence of any test. Though we should always close streams, doing so is also a distraction.
Using @After
and @Before
methods
To remedy this issue, let’s move the bits of clutter to @Before
and @After
methods. To allow both tests to take advantage of the stream.close()
in the @After
method, change the second test to reference the stream field instead of the local variable named inputStream
.
We should also look at the line that reads:
We also ponder the line that reads:
assertFalse(search.errored());
The above assertion isn’t an irrelevant detail since it’s a valid assertion. We might consider it as a second postcondition of running a search, but it hints at something deeper. Namely, it prompts us to ask where is the test case that generates a true value for search.errored()
? Delete the assertion and make a note to add a third (and maybe also a fourth) test before committing.
Challenge
Here are the decluttering changes:
- Add the following
@Before
in the code (lines 15-18).
@Before
public void turnOffLogging() {
Search.LOGGER.setLevel(Level.OFF);
}
- Add the following
@After
in the code (lines 20-23).
@After
public void closeResources() throws IOException {
stream.close();
}
Get hands-on with 1400+ tech skills courses.