0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · บทเรียน

ฐานข้อมูลฝังตัวสำหรับการทดสอบ

กำหนดค่าและใช้ฐานข้อมูลในหน่วยความจำหรือฐานข้อมูลฝังตัวเพื่อการทดสอบการผสานรวมที่รวดเร็วและแยกเป็นอิสระ

ฐานข้อมูลฝังตัวสำหรับการทดสอบ เป็นบทเรียน Testing Mastery: JUnit, Mockito & Integration Tests ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Testing Mastery: JUnit, Mockito & Integration Tests และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Testing Mastery: JUnit, Mockito & Integration Tests มีบทเรียนทั้งหมด 4 บทเรียน

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

Embedded DBs for Tests

When writing integration tests for Spring Boot applications, especially those interacting with a database, you need a database instance for your tests to run against.

Embedded databases provide a lightweight, in-memory solution that's perfect for this scenario.

Why Use Embedded DBs?

Embedded databases offer several key benefits for testing:

  • Isolation: Each test run gets a clean, fresh database, preventing side effects.
  • Speed: Being in-memory, they are incredibly fast, reducing test execution time.
  • Simplicity: No need for external database servers or complex setup.
  • Repeatability: Tests are consistent because they always start with the same data state.

H2 & HSQLDB Options

Two popular choices for embedded databases in Java applications are H2 Database and HSQLDB.

  • H2: A fast, open-source, JDBC-compliant in-memory database. It's widely used with Spring Boot.
  • HSQLDB: Another lightweight, relational database written in Java.

We'll focus on H2 as it's a common default in Spring Boot.

Adding H2 Dependency

To use H2 in your Spring Boot project, you typically add it as a test scope dependency in your pom.xml (for Maven) or build.gradle (for Gradle).

This ensures it's only available during testing.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

Spring Boot Auto-Config

One of Spring Boot's magic tricks is auto-configuration. When it detects H2 on the classpath during tests, it automatically configures an in-memory H2 database for you.

You often don't need to specify a database URL in application.properties for tests, making setup trivial!

User Entity & Repository

Let's consider a simple User entity and a UserRepository. We want to test if our repository correctly saves and retrieves users.

These are standard JPA components.

// User.java
package com.coddykit.demo;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    public User() {}
    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // Getters and Setters
    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; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

// UserRepository.java
package com.coddykit.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

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

@DataJpaTest with H2

Spring Boot provides @DataJpaTest specifically for testing JPA components. It auto-configures an in-memory database (like H2 if present) and an EntityManager.

It also rolls back transactions after each test, ensuring a clean state.

UserRepository Test Example

Here's how you might write an integration test for our UserRepository using H2 and @DataJpaTest:

package com.coddykit.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private UserRepository userRepository;

    @Test
    void whenFindByName_thenReturnUser() {
        // given
        User alice = new User("Alice", "alice@example.com");
        entityManager.persist(alice);
        entityManager.flush();

        // when
        User found = userRepository.findByName(alice.getName());

        // then
        assertThat(found.getName()).isEqualTo(alice.getName());
        assertThat(found.getEmail()).isEqualTo(alice.getEmail());
    }

    @Test
    void whenInvalidName_thenReturnNull() {
        // when
        User found = userRepository.findByName("InvalidName");

        // then
        assertThat(found).isNull();
    }
}

Schema & Data Initialization

For more complex scenarios, you might need to pre-populate your in-memory database with a schema or initial data.

  • Place schema.sql in src/test/resources for DDL (Data Definition Language).
  • Place data.sql in src/test/resources for DML (Data Manipulation Language).

Spring Boot will automatically pick these up for your tests.

Quick Check

Which of the following is NOT a primary benefit of using an embedded database like H2 for Spring Boot integration tests?

Recap & Next Steps

We've explored how embedded databases like H2 are invaluable for fast and isolated Spring Boot integration tests.

  • They offer speed, isolation, and simplicity.
  • Spring Boot auto-configures them with minimal effort.
  • @DataJpaTest simplifies testing JPA repositories with these databases.
  • You can initialize schemas and data using schema.sql and data.sql.

Next, you might explore testing RESTful APIs with MockMvc!

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

บทเรียน “ฐานข้อมูลฝังตัวสำหรับการทดสอบ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “ฐานข้อมูลฝังตัวสำหรับการทดสอบ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Testing Mastery: JUnit, Mockito & Integration Tests ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Testing Mastery: JUnit, Mockito & Integration Tests มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “ฐานข้อมูลฝังตัวสำหรับการทดสอบ”

กำหนดค่าและใช้ฐานข้อมูลในหน่วยความจำหรือฐานข้อมูลฝังตัวเพื่อการทดสอบการผสานรวมที่รวดเร็วและแยกเป็นอิสระ คุณปฏิบัติ Testing Mastery: JUnit, Mockito & Integration Tests ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Testing Mastery: JUnit, Mockito & Integration Tests หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Testing Mastery: JUnit, Mockito & Integration Tests บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “ฐานข้อมูลฝังตัวสำหรับการทดสอบ” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Testing Mastery: JUnit, Mockito & Integration Tests นี้ได้ไหม

ได้ บทเรียน Testing Mastery: JUnit, Mockito & Integration Tests ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. เฟรมเวิร์กบริบทการทดสอบของ Spring
  2. การทดสอบ API แบบ RESTful
  3. ฐานข้อมูลฝังตัวสำหรับการทดสอบ
  4. การทดสอบชั้นเว็บด้วย @WebMvcTest และ MockMvc
← กลับไปที่ Testing Mastery: JUnit, Mockito & Integration Tests