0Pricing
Spring Boot 4 Complete Guide · บทเรียน

การทดสอบการผสานรวมด้วย Spring Boot

ดำเนินการทดสอบการผสานรวมสำหรับตัวควบคุม REST และคลังข้อมูลของคุณโดยใช้ `@SpringBootTest`

การทดสอบการผสานรวมด้วย Spring Boot เป็นบทเรียน Spring Boot 4 Complete Guide ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Complete Guide และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What is Integration Testing?

Welcome to integration testing with Spring Boot! So far, you've learned about unit testing, which isolates small pieces of code.

Integration tests, on the other hand, verify that different components of your application work correctly together. This often involves multiple layers, like your web controller, service, and even the database.

  • They test the 'glue' between components.
  • They catch issues that unit tests might miss.
  • They provide higher confidence in your application's behavior.

@SpringBootTest Annotation

The cornerstone of integration testing in Spring Boot is the @SpringBootTest annotation.

When you use @SpringBootTest, it loads the full Spring application context. This means all your beans (components), configurations, and properties are initialized, just like when your application starts normally.

It's powerful, but also heavier and slower than unit tests because it brings up more of your application.

A Simple Service Example

Let's imagine a simple greeting service that we want to test. This service will be part of our Spring Boot application.

Run this code to see the application context start, though it won't do much without an endpoint.

package com.coddykit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

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

@Service
class GreetingService {
  public String greet(String name) {
    return "Hello, " + name + "!";
  }
}

Testing a Service with @SpringBootTest

Here's how you'd write an integration test for our GreetingService. Notice we @Autowired the service directly.

When this test runs, @SpringBootTest ensures the GreetingService bean is available in the test context.

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class GreetingServiceIT {

  @Autowired
  private GreetingService greetingService;

  @Test
  void contextLoads() {
    assertThat(greetingService).isNotNull();
  }

  @Test
  void greetReturnsCorrectMessage() {
    String result = greetingService.greet("Coddy");
    assertThat(result).isEqualTo("Hello, Coddy!");
  }
}

Testing Web Layer with MockMvc

For testing REST controllers, we often don't want to start a full HTTP server. This is where MockMvc comes in.

MockMvc allows you to perform requests against your controllers in a simulated environment, without needing an actual running server. It's faster and more controlled.

  • Use @AutoConfigureMockMvc with @SpringBootTest.
  • Inject MockMvc to make requests.
  • Assert on status, content, and headers.

A Simple REST Controller

Let's add a simple REST controller to our application. This controller uses our GreetingService.

Run this code to start the application with the controller. You could access /api/greet?name=World in a browser if you had a full setup.

package com.coddykit;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;

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

@RestController
class GreetingController {
  private final GreetingService greetingService;

  @Autowired
  public GreetingController(GreetingService service) {
    this.greetingService = service;
  }

  @GetMapping("/api/greet")
  public String greetUser(@RequestParam String name) {
    return greetingService.greet(name);
  }
}

@Service
class GreetingService {
  public String greet(String name) {
    return "Hello, " + name + "!";
  }
}

Testing GET Requests with MockMvc

Here's how to test our GreetingController's GET endpoint using MockMvc. We simulate an HTTP GET request to /api/greet with a query parameter.

We then assert that the HTTP status is OK (200) and the response content matches our expectation.

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;

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
class GreetingControllerIT {

  @Autowired
  private MockMvc mockMvc;

  @Test
  void greetUserEndpointReturnsCorrectMessage() throws Exception {
    mockMvc.perform(get("/api/greet?name=Coddy"))
           .andExpect(status().isOk())
           .andExpect(content().string("Hello, Coddy!"));
  }
}

Testing POST Requests

Testing POST requests with MockMvc is similar but involves specifying the HTTP method and potentially a request body. You often need to set the Content-Type header.

For example, if you had an endpoint to create a new user, you'd send a JSON payload in the request body.

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

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;

// Assuming a controller with @PostMapping("/api/users")
// and a method accepting @RequestBody User user

@SpringBootTest
@AutoConfigureMockMvc
class UserControllerIT {

  @Autowired
  private MockMvc mockMvc;

  @Test
  void createUserEndpointReturnsCreatedStatus() throws Exception {
    String newUserJson = "{\"name\":\"Jane Doe\", \"email\":\"jane@example.com\"}";

    mockMvc.perform(post("/api/users")
           .contentType(MediaType.APPLICATION_JSON)
           .content(newUserJson))
           .andExpect(status().isCreated()); // Expect HTTP 201 Created
  }
}

Testing Data Repositories

When testing your data layer (repositories), @SpringBootTest can also be used. You can @Autowired your repository interfaces directly.

It's common to use an in-memory database like H2 for these tests to ensure they are fast and don't affect your development database. Also, @Transactional can ensure tests clean up after themselves.

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

// Example Entity (e.g., in src/main/java/com/coddykit/User.java)
// public class User { private Long id; private String name; /* getters/setters */ }

// Example Repository (e.g., in src/main/java/com/coddykit/UserRepository.java)
interface User {
  Long getId();
  void setId(Long id);
  String getName();
  void setName(String name);
}

@Repository
interface UserRepository extends CrudRepository<User, Long> {
  User findByName(String name);
}

@SpringBootTest
@Transactional // Each test runs in a transaction and rolls back
class UserRepositoryIT {

  @Autowired
  private UserRepository userRepository;

  @Test
  void findByNameReturnsUser() {
    // Create and save a user for the test
    // (In a real scenario, User would be a JPA @Entity)
    User user = new User() {
      private Long id;
      private String name;
      public Long getId() { return id; }
      public void setId(Long id) { this.id = id; }
      public String getName() { return name; }
      public void setName(String name) { this.name = name; }
    };
    user.setName("TestUser");
    userRepository.save(user);

    User foundUser = userRepository.findByName("TestUser");
    assertThat(foundUser).isNotNull();
    assertThat(foundUser.getName()).isEqualTo("TestUser");
  }
}

Quick Check on @SpringBootTest

You've learned how @SpringBootTest helps with integration tests. Let's see if you can recall its primary function.

Recap: Integration Testing

Great job! You've explored the world of integration testing in Spring Boot.

  • @SpringBootTest loads the entire application context for comprehensive tests.
  • MockMvc allows you to simulate HTTP requests against your controllers without a running server, making web layer tests faster and more reliable.
  • You can test service and repository layers by autowiring them directly into @SpringBootTest classes, often with an in-memory database.

Integration tests are crucial for verifying that all parts of your Spring Boot application work harmoniously.

คำถามที่พบบ่อย

บทเรียน “การทดสอบการผสานรวมด้วย Spring Boot” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การทดสอบการผสานรวมด้วย Spring Boot” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Complete Guide ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Complete Guide มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การทดสอบการผสานรวมด้วย Spring Boot”

ดำเนินการทดสอบการผสานรวมสำหรับตัวควบคุม REST และคลังข้อมูลของคุณโดยใช้ `@SpringBootTest` คุณปฏิบัติ Spring Boot 4 Complete Guide ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Complete Guide หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Complete Guide บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การทดสอบการผสานรวมด้วย Spring Boot” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Complete Guide นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Complete Guide ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การทดสอบหน่วยด้วย JUnit และ Mockito
  2. การทดสอบการผสานรวมด้วย Spring Boot
  3. การทดสอบแบบแยกส่วนและ TestContainers
  4. การทดสอบเว็บคอนโทรลเลอร์ด้วย MockMvc
← กลับไปที่ Spring Boot 4 Complete Guide