0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · 课时

用于测试的嵌入式数据库

配置并使用内存数据库或嵌入式数据库,以便快速、隔离地进行集成测试。

用于测试的嵌入式数据库 是 CoddyKit 上的免费 Testing Mastery: JUnit, Mockito & Integration Tests 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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 导师)并解锁 Testing Mastery: JUnit, Mockito & Integration Tests 课程的其余内容,请升级到 CoddyKit PRO。 Testing Mastery: JUnit, Mockito & Integration Tests 课程共包含 4 节课。

「用于测试的嵌入式数据库」这节课中我会学到什么?

配置并使用内存数据库或嵌入式数据库,以便快速、隔离地进行集成测试。 你通过在浏览器中直接运行的动手代码来练习 Testing Mastery: JUnit, Mockito & Integration Tests,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Testing Mastery: JUnit, Mockito & Integration Tests 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Testing Mastery: JUnit, Mockito & Integration Tests 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「用于测试的嵌入式数据库」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Testing Mastery: JUnit, Mockito & Integration Tests 课中编写并运行代码吗?

能。每节 Testing Mastery: JUnit, Mockito & Integration Tests 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Spring 测试上下文框架
  2. 测试 RESTful API
  3. 用于测试的嵌入式数据库
  4. 使用 @WebMvcTest 与 MockMvc 测试 Web 层
← 返回 Testing Mastery: JUnit, Mockito & Integration Tests