Unit Tests and Spring Boot

May 24, 2017

I have been practicing test driven development (TDD) in Java for a couple
of years now. Recently, I started using Spring Boot framework. Spring Boot doesn’t require XML configuration.
I can use @Autowired annotation to direct Spring Boot to inject the dependency for me. With my new found love for Spring Boot,
I wrote the following unit test for a project I had been working on.

I wrote a few more tests this way for my project before I realized I was doing something wrong. By using @Autowired here I made my test
depend on Spring Boot framework. I had to also annotate my test class with @RunWith(SpringRunner.class)
and @SpringBootTest to support @Autowired. By writing the test this way, every time I run the unit test, Spring boot fires up the
embedded server to run the test. As a result, my test suite took longer to run.

Overuse of framework

My unit test is trying to test a simple method tokenizeString() which takes an input string and returns tokens. There is nothing
here that requires me to depend on Spring Boot framework. I did not need to use @Autowired to initialize tokenService object.
I could have initialized my object the old fashioned way TokenService tokenService = new TokenService().

Once I got rid of @Autowired, I did not need @SpringBootTest and @RunWith annotations.

Here’s the refactored test

publicclassTokenServiceTests{TokenServicetokenService=newTokenService();@TestpublicvoidtokenizeStringTest(){StringstringToTokenize="How do I pay my bill online?";Set<String>expectedTokens=newHashSet<>(Arrays.asList("how","do","i","pay","my","bill","online"));Set<String>actualTokens=tokenService.tokenizeString(stringToTokenize);assertThat(actualTokens).isEqualTo(expectedTokens);}}//Omitted for brevity

The refactored test looks cleaner and runs faster.

When to depend on framework in a unit test?

There are many instances when using framework in a unit test is necessary. For instance, I like to write unit tests for a REST controller to test my end points.