0
votes

I am very new to Spring Boot and trying to learn how testing should be done in Spring Boot. I read about the @SpringBootTest annotation which helps in integration testing an application. I was wondering how unit testing should be done in spring boot. Does unit testing require specifying the @SpringBootTest annotation or is that to be used only for integration testing? Are there specific annotations to be used for unit testing?

Any pointers would be much appreciated. Thanks in advance!

Edit: Is the SpringBootTest annotation used only for integration testing? I found the following code example in the Spring documentation:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

@Autowired
private MockMvc mvc;

@Test
public void getHello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}

Is this a unit or integration test? My guess is its not an integration test since it uses a MockMvc. Is that right? If so, does this mean that the @SpringBootTest annotation can be used for tests which are not full fledged integration tests?

2
You don't need anything special to do unit testing. Just use new to create your component under test. - JB Nizet
As @JBNizet said, you don't need anything special to unit test your classes in a Spring Boot application. Just code and run your test classes the way you would do if you weren't using Spring Boot. But if what you want to know is how to make a test for HTTP calls to your endpoints (which would be an integration test, not a unit test), I can help; just say so in your post. - walen
Thanks for responding, I am aware that Spring Boot provides very advanced integration testing capabilities. I understand that Spring Boot provides a slice testing feature whereby individual components of an application can be tested. For ex. the WebMvcTest annotation can be used to test the controller part. Can this be considered unit testing? - Revansha
Also, I understand that the "spring-boot-starter-test" dependency needs to be added to the pom file to add testing support. What does this dependency do? Should this be used only for integration testing? - Revansha

2 Answers

1
votes

Strictly speaking, "unit" tests should not use Spring. Just use JUnit/TestNG/Spock/whatever, like you normally would, to test the individual classes. @SpringBootTest is for integration, and beyond, tests.

0
votes

This is what I would do: For Integration Testing end-to-end:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTests {

    @Autowired
    private TestRestTemplate restTemplate;
    @Autowired
    private CarRepository repository;
    @Autowired
    private CarService carService;

    @Test
    public void contextLoads() {
    }

    @Test
    public void basicTest() {
        String body = this.restTemplate.getForObject("/", String.class);
        assertThat(body).contains("Not Found");
    }
}

For testing a controller only (controller unit test):

    @RunWith(SpringRunner.class)
    @WebMvcTest(controllers = CarController.class, excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
    public class ControllerTests {

        @Autowired
        private MockMvc mvc;

        @MockBean
        private CarRepository carRepository;

        @MockBean
        private MongoTemplate mongoTemplatel;

        @Test
        public void testGet() throws Exception {
            short year = 2010;
            given(this.carRepository.findByVin("ABC"))
                    .willReturn(new Car("ABC", "Honda", "Accord", year, 100000, "Red", "Ex-V6"));
            this.mvc.perform(get("/car").param("VIN", "ABC").accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk()).andExpect(content().string("[{\"vin\":\"ABC\",\"make\":\"Honda\",\"model\":\"Accord\",\"year\":2010,\"mileage\":100000,\"color\":\"Red\",\"trim\":\"Ex-V6\",\"type\":null,\"maintenanceTasksList\":[\"Oil Change\",\"Tire Rotation\"]}]"));
        }
    }

You can find a complete Spring Boot application that include Integration and Unit tests here.