jon
jon

Reputation: 245

I want to test a controller without using @SpringBootTest

I have the following test class:

@SpringBootTest
public class ChoreControllerTest
{
    @Autowired 
    private ChoreController controller;

    @Test
    public void throwOnMissingChore()
    {
        assertThrows(ChoreNotFoundException.class, () -> this.controller.getChore(0L));
    }
}

It takes about 5 seconds for Spring Boot to start up so the test can run. I want to reduce this time, but if I just remove the @SpringBootTest annotaton, I just get a NPE.

Is there a way to make this controller test more lightweight, or am I stuck with the startup time? I'm especially worried about what will happen to my test times if I ever want to test more than one controller....

Upvotes: 6

Views: 2702

Answers (1)

tobhai
tobhai

Reputation: 462

The @SpringBootTest annotations create a Spring Context for you therefore it takes a while to start up. This annotation is mostly used for integration tests where a Spring context is required. Here are a few tips for optimizing integration tests. If you remove the annotation the ChoreController cannot be autowired (no context available) which results in a NullpointerException.
Depending on your needs you can just use a Mocking library like Mockito to inject mocks e.g. services that your controller class needs and run the test without the @SpringBootTest.

You might want to take a look at this article for setting up those mocks properly.

Upvotes: 5

Related Questions