What You'll Learn

We want to write automated tests of our Spring Boot application. But, Spring Boot applications are based on the Spring container and handle web and database interactions. How can we test efficiently and effectively in this situation?

In previous tags, we had added this test.

CharitySearches.java

@Test
    public void shouldGet4Charities() throws Exception {
        List<CharityDTO> charityDTOList = charityService.findAll();
        assertEquals(4, charityDTOList.size());
    }

This was fine when we were constructing the charityService object ourselves, but now Spring is doing that for us. Just putting @Autowired on the declaration won't help because the test code is just JUnit-based. It won't create the Spring container and therefore, there won't be an instance to call.

Try it - check out previous revisions and see when the test passed and when it started failing.

Fortunately, making the test Spring-aware is straight-forward. We add the @SpringBootTest annotation to the test class.

CharitySearches.java

@SpringBootTest
public class CharitySearches {

    @Autowired
    private CharitySearch charityService;

    @Test
    public void shouldGet4Charities() throws Exception {
        List<CharityDTO> charityDTOList = charityService.findAll();
        assertEquals(11, charityDTOList.size());
    }
}

Now, when this test is run, a Spring container will be created and the beans will be available to the tests. The H2 database will be instantiated as well, so this test is an "integration" test since it calls the service, that calls the repository that calls the database. These tests can be useful, but they are also slow (since there is more to instantiate), less reliable (there are more moving parts) and less focussed (if the test fails, there are more places to look).

Run the test, either in IntelliJ or via Gradle > Build > build.

We've added a single, whole container, Spring test. We'll see other options are available that are not focussed on certain parts of the architecture.

Research Spring's other testing facilities and references.