0
0
SpringbootHow-ToBeginner · 4 min read

How to Test REST API in Spring Boot: Simple Guide

To test a REST API in Spring Boot, use @SpringBootTest with MockMvc to simulate HTTP requests and verify responses. This allows you to write integration tests that check your API endpoints without running the full server.
📐

Syntax

Use @SpringBootTest to load the full application context and @AutoConfigureMockMvc to enable MockMvc for HTTP request simulation. Inject MockMvc and use its methods to perform requests and assert responses.

  • @SpringBootTest: Starts the Spring context for integration testing.
  • @AutoConfigureMockMvc: Configures MockMvc for testing controllers.
  • MockMvc.perform(): Simulates HTTP requests.
  • andExpect(): Checks the response status, content, and headers.
java
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.beans.factory.annotation.Autowired;
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.status;
import org.junit.jupiter.api.Test;

@SpringBootTest
@AutoConfigureMockMvc
public class ApiTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGetEndpoint() throws Exception {
        mockMvc.perform(get("/api/example"))
               .andExpect(status().isOk());
    }
}
💻

Example

This example shows a simple Spring Boot REST controller and a test class that verifies the GET endpoint returns HTTP 200 OK with expected JSON content.

java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@RestController
class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}

// Test class
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void helloEndpointReturnsMessage() throws Exception {
        mockMvc.perform(get("/hello"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello, Spring Boot!"));
    }
}
Output
Tests passed: 1, Failures: 0, Errors: 0
⚠️

Common Pitfalls

Common mistakes when testing REST APIs in Spring Boot include:

  • Not using @AutoConfigureMockMvc, so MockMvc is not set up.
  • Forgetting to annotate test methods with @Test, so tests don't run.
  • Using @WebMvcTest without mocking dependencies, causing context load failures.
  • Not handling JSON serialization/deserialization properly in request or response.

Always check your test annotations and context setup.

java
/* Wrong way: Missing @AutoConfigureMockMvc causes NullPointerException on MockMvc injection */
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
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.status;

@SpringBootTest
public class WrongTest {
    @Autowired
    private MockMvc mockMvc; // This will be null

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/hello")) // NullPointerException
               .andExpect(status().isOk());
    }
}

/* Right way: Add @AutoConfigureMockMvc to enable MockMvc injection */
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.beans.factory.annotation.Autowired;
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.status;

@SpringBootTest
@AutoConfigureMockMvc
public class RightTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/hello"))
               .andExpect(status().isOk());
    }
}
📊

Quick Reference

  • @SpringBootTest: Loads full Spring context for integration tests.
  • @AutoConfigureMockMvc: Enables MockMvc for HTTP request simulation.
  • MockMvc.perform(): Simulates HTTP calls to your controllers.
  • andExpect(): Asserts response status, headers, and body.
  • @Test: Marks test methods to run.

Key Takeaways

Use @SpringBootTest with @AutoConfigureMockMvc to test REST APIs in Spring Boot.
Inject MockMvc to simulate HTTP requests and verify responses without starting a server.
Annotate test methods with @Test to ensure they run.
Avoid missing @AutoConfigureMockMvc to prevent NullPointerException on MockMvc.
Use andExpect() to check HTTP status and response content precisely.