การทดสอบหน่วยด้วย JUnit และ Mockito
ทดสอบองค์ประกอบแยกจากกัน
การทดสอบหน่วยด้วย JUnit และ Mockito เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Microservices & REST APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Unit Tests
A unit test verifies a single class in isolation, with its collaborators replaced by fakes.
- Fast — no Spring context, no database
- Focused — tests one piece of logic
- Reliable — no external dependencies
JUnit 5 Basics
Spring Boot uses JUnit 5 (Jupiter). A test is a method annotated with @Test.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void addsTwoNumbers() {
assertEquals(5, 2 + 3);
}
}Lifecycle Annotations
Use @BeforeEach to set up state before each test and @AfterEach to clean up.
@BeforeEach
void setUp() {
calculator = new Calculator();
}
@Test
void addsCorrectly() {
assertEquals(7, calculator.add(3, 4));
}AssertJ Fluent Assertions
Spring Boot bundles AssertJ for readable assertions with assertThat.
import static org.assertj.core.api.Assertions.assertThat;
assertThat(result).isEqualTo(42);
assertThat(list).hasSize(3).contains("a");What is Mockito
Mockito creates mock objects — fake implementations of dependencies whose behavior you control.
This lets you test a class without its real collaborators (database, HTTP clients, etc.).
Creating Mocks
Annotate the test class with @ExtendWith(MockitoExtension.class). Use @Mock for dependencies and @InjectMocks for the class under test.
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
UserRepository repository;
@InjectMocks
UserService service;
}Stubbing with when/thenReturn
Define a mock's behavior with when(...).thenReturn(...).
@Test
void returnsUserById() {
User alice = new User("1", "Alice");
when(repository.findById("1"))
.thenReturn(Optional.of(alice));
User result = service.getById("1");
assertThat(result.getName()).isEqualTo("Alice");
}Throwing from a Mock
Use thenThrow to simulate error conditions.
when(repository.findById("99"))
.thenThrow(new RuntimeException("DB down"));
assertThrows(RuntimeException.class,
() -> service.getById("99"));Verifying Interactions
verify checks that a mock method was called with expected arguments.
@Test
void savesUser() {
service.create(new User("2", "Bob"));
verify(repository).save(any(User.class));
verify(repository, times(1)).save(any());
}Argument Matchers
Matchers like any(), eq(), and anyString() make stubs flexible.
when(repository.findByName(anyString()))
.thenReturn(List.of(new User("1", "Alice")));
verify(repository).deleteById(eq("1"));Capturing Arguments
ArgumentCaptor captures the value passed to a mock so you can assert on it.
ArgumentCaptor<User> captor =
ArgumentCaptor.forClass(User.class);
verify(repository).save(captor.capture());
assertThat(captor.getValue().getName())
.isEqualTo("Bob");Quick Check
Test your understanding of Mockito.
Recap
You learned to write fast unit tests:
- JUnit 5 with
@Test,@BeforeEach - AssertJ
assertThatfor readable checks - Mockito
@Mock/@InjectMocks when/thenReturnto stub,verifyto confirm calls
คำถามที่พบบ่อย
บทเรียน “การทดสอบหน่วยด้วย JUnit และ Mockito” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การทดสอบหน่วยด้วย JUnit และ Mockito” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การทดสอบหน่วยด้วย JUnit และ Mockito”
ทดสอบองค์ประกอบแยกจากกัน คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การทดสอบหน่วยด้วย JUnit และ Mockito” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม
ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การทดสอบหน่วยด้วย JUnit และ Mockito
- การทดสอบชั้นเว็บด้วย MockMvc
- การทดสอบการผสานรวมด้วย @SpringBootTest
- ส่วนพึ่งพาจริงด้วย Testcontainers