如何在Spring中用JUnit Jupiter测试EntityManager原生SQL方法?
测试Spring中基于Native Query的Transactional方法(JUnit Jupiter)
针对你提供的包含EntityManager和@Transactional的方法,用Spring + JUnit Jupiter可以按以下步骤完成测试:
1. 确保测试依赖齐全
如果是Spring Boot项目,直接引入spring-boot-starter-test和H2内存数据库依赖(用于模拟测试环境,避免操作真实数据库):
Maven pom.xml示例:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>
Gradle build.gradle示例:
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'com.h2database:h2'
2. 编写测试类
测试类需要加载Spring上下文,并注入待测试的服务类。核心代码示例如下:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import javax.persistence.PersistenceContext; import javax.persistence.EntityManager; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest @Transactional // 测试方法默认回滚,避免污染测试环境 class DataMigrationServiceTest { // 假设你的方法在DataMigrationService类中 @Autowired private DataMigrationService targetService; // 注入待测试的类 @PersistenceContext private EntityManager em; // 用于准备测试数据和验证结果 @Test void sendToTableOne_ShouldInsertDataFromTableTwo() { // 步骤1:准备测试数据——往TABLE_TWO插入一条测试记录 em.createNativeQuery("INSERT INTO TABLE_TWO (col1, col2) VALUES ('test_val1', 'test_val2')") .executeUpdate(); // 步骤2:调用待测试的方法 int affectedRows = targetService.sendToTableOne(); // 步骤3:验证执行结果 // 确认返回的受影响行数符合预期 assertEquals(1, affectedRows); // 验证TABLE_ONE中确实存在这条数据 Long tableOneCount = (Long) em.createNativeQuery("SELECT COUNT(*) FROM TABLE_ONE").getSingleResult(); assertEquals(1, tableOneCount); } }
3. 配置测试用数据库
在src/test/resources下创建application-test.yml(或application.properties),配置H2内存数据库,让Spring自动创建测试用的表结构:
spring: datasource: url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 driver-class-name: org.h2.Driver username: sa password: jpa: hibernate: ddl-auto: create-drop # 每次测试前创建表,测试结束后删除 show-sql: true # 可选,开启后可以查看执行的SQL语句,方便调试
4. 关键注意事项
- 事务回滚:
@Transactional注解会让测试方法执行完后自动回滚所有操作,不需要手动清理测试数据 - 非Spring Boot项目适配:如果不是Spring Boot项目,需要用
@ContextConfiguration指定Spring配置类,确保EntityManagerFactory、TransactionManager等核心Bean被正确加载 - 表结构匹配:确保TABLE_ONE和TABLE_TWO的表结构一致,否则Native Query的
SELECT *会抛出字段不匹配的异常
内容的提问来源于stack exchange,提问作者Marcos
相关产品推荐
相关产品推荐

