0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · 강의

REST 방식 API 테스트

`MockMvc` 또는 `WebTestClient`를 사용해 Spring Boot REST 컨트롤러를 위한 종합적인 통합 테스트를 작성합니다.

REST 방식 API 테스트은(는) CoddyKit의 무료 Testing Mastery: JUnit, Mockito & Integration Tests 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Testing Mastery: JUnit, Mockito & Integration Tests 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Test REST APIs?

RESTful APIs are the backbone of many modern applications. Testing them is crucial to ensure they work as expected, handle various inputs, and return correct responses.

This lesson focuses on how to write integration tests for your Spring Boot REST controllers using powerful tools: MockMvc and WebTestClient.

Spring Boot Test Setup

To test Spring Boot controllers, we need a special setup. The @SpringBootTest annotation loads the full application context, and @AutoConfigureMockMvc configures MockMvc for us.

Here's a basic structure for a controller test class:

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;

@SpringBootTest
@AutoConfigureMockMvc
public class MyApiControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void contextLoads() {
        // Your tests will go here
    }
}

Introducing MockMvc

MockMvc allows you to test your Spring MVC controllers without starting a full HTTP server. It simulates HTTP requests and responses, making tests fast and isolated.

It's ideal for testing the controller layer, ensuring routes, request mappings, and response formats are correct.

MockMvc: Testing GET Requests

Let's test a simple GET endpoint, for example, /api/hello which returns "Hello, CoddyKit!". We'll verify the HTTP status code and the response content.

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.http.MediaType;
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;

// Assume a @RestController with @GetMapping("/api/hello") returning "Hello, CoddyKit!"
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHelloEndpoint() throws Exception {
        mockMvc.perform(get("/api/hello"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello, CoddyKit!"));
    }
}

MockMvc: GET with Path Variables

APIs often use path variables to identify resources, like /api/users/{id}. MockMvc handles these naturally.

Here's how to test an endpoint that takes an ID:

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.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

// Assume @GetMapping("/api/users/{id}") returns "User: " + id
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testGetUserById() throws Exception {
        mockMvc.perform(get("/api/users/{id}", 123))
               .andExpect(status().isOk())
               .andExpect(content().string("User: 123"));
    }
}

MockMvc: Testing POST Requests

For POST requests, you typically send a request body, often in JSON format. We can specify the content type and body using MockMvc.

Let's test an endpoint that creates an item:

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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

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

// Assume @PostMapping("/api/items") creates an item and returns it
@SpringBootTest
@AutoConfigureMockMvc
public class ItemControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testCreateItem() throws Exception {
        String newItemJson = "{\"name\":\"Laptop\", \"price\":1200}";
        mockMvc.perform(post("/api/items")
                       .contentType(MediaType.APPLICATION_JSON)
                       .content(newItemJson))
               .andExpect(status().isCreated())
               .andExpect(jsonPath("$.name").value("Laptop"));
    }
}

Introducing WebTestClient

WebTestClient is a non-blocking, reactive client for testing web applications. It's part of Spring WebFlux but can also be used to test Spring MVC controllers.

  • It can perform actual HTTP calls (if configured to hit a running server).
  • It can also be backed by MockMvc for server-side testing similar to MockMvc itself, but with a reactive API.

WebTestClient in Action

Using WebTestClient is similar to MockMvc, but its fluent API often feels more modern, especially for reactive applications. Let's re-test our /api/hello endpoint.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.web.reactive.server.WebTestClient;

// For WebTestClient with Spring MVC, we can use @SpringBootTest
// and inject WebTestClient.Builder to build it with MockMvc.webAppContextSetup
// For simplicity, this example assumes a WebFlux app or WebTestClient set up for MockMvc
// @SpringBootTest
// class HelloWebClientTest {
// @Autowired WebApplicationContext wac;
// WebTestClient client;
// @BeforeEach void setup() { client = WebTestClient.bindToApplicationContext(wac).build(); }
// ...

// For a simpler runnable example focusing on WebTestClient usage:
@WebFluxTest // This annotation sets up a minimal reactive context for WebTestClient
public class HelloWebClientTest {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    void testHelloEndpoint() {
        webTestClient.get().uri("/api/hello")
                     .exchange()
                     .expectStatus().isOk()
                     .expectBody(String.class).isEqualTo("Hello, CoddyKit!");
    }
}

MockMvc vs. WebTestClient

When should you use MockMvc versus WebTestClient?

  • MockMvc: Best for traditional Spring MVC applications. It's server-side, simulates requests, and doesn't require a running server, making it fast.
  • WebTestClient: Ideal for reactive Spring WebFlux applications. It also provides a reactive client API for testing Spring MVC apps, offering a more modern, fluent way to write tests, and can even hit a live server for true end-to-end integration tests.

For most Spring Boot REST API integration tests focusing on the controller layer, MockMvc is a solid choice due to its speed and direct integration.

Quick Check: API Testing Tools

You are building a Spring Boot application using traditional Spring MVC. You want to write fast, isolated integration tests for your REST controllers without starting a full HTTP server.

Recap & Next Steps

In this lesson, you learned how to write comprehensive integration tests for your Spring Boot REST controllers. We covered:

  • Setting up your test environment with @SpringBootTest and @AutoConfigureMockMvc.
  • Using MockMvc to simulate GET and POST requests, verifying status and content.
  • Introducing WebTestClient for reactive testing and its alternative use cases.
  • Understanding the differences and when to choose between MockMvc and WebTestClient.

These tools are essential for building robust and reliable RESTful APIs!

자주 묻는 질문

“REST 방식 API 테스트” 강의는 무료인가요?

네 — “REST 방식 API 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Testing Mastery: JUnit, Mockito & Integration Tests 강의 전체를 잠금 해제할 수 있습니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.

“REST 방식 API 테스트”에서 뭘 배우나요?

`MockMvc` 또는 `WebTestClient`를 사용해 Spring Boot REST 컨트롤러를 위한 종합적인 통합 테스트를 작성합니다. 브라우저에서 직접 실행하는 실습 코드로 Testing Mastery: JUnit, Mockito & Integration Tests을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Testing Mastery: JUnit, Mockito & Integration Tests을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Testing Mastery: JUnit, Mockito & Integration Tests은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“REST 방식 API 테스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Testing Mastery: JUnit, Mockito & Integration Tests 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Spring 테스트 컨텍스트 프레임워크
  2. REST 방식 API 테스트
  3. 테스트용 임베디드 데이터베이스
  4. @WebMvcTest와 MockMvc로 웹 계층 테스트하기
← Testing Mastery: JUnit, Mockito & Integration Tests(으)로 돌아가기