Skip to content
GitHub Twitter

Writing an API Test in Spring Boot

Do you trust your code? I don’t, that’s why I write automated tests for it.

In this blog you will see how writing an API Test in Spring Boot looks like, and what do you need in order to achieve that.

Obviously the first step is having the right dependencies on your classpath, and because the Spring Boot team is amazing, they wrapped everything needed in the spring-boot-starter-test dependency.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

img.png

As you can see, by default your test will use the properties and configuration from your spring boot entry point.

Given you have an endpoint that returns a list of strings, a very simple example but you get the idea 😁

public class RestController{
    
    @GetMapping("/data")
    public List<String> getData(){
        return Arrays.asList("String1","String2");
    }
}

In order to write an API test for this endpoint, we can use something called MockMvc which comes from the org.springframework.test module which will execute the requests but also assert the test. Our test will execute the request to this endpoint, ensure the status code is 200 but also the first string on the result will be String1. The code looks like this

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest(classes = ApiTestsInSpringBootApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc()
class DataControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    void getData() throws Exception {

        mvc.perform(get("/data"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("[0]").value("String1"));
    }
}