【单元测试】Spring Data JPA + H2 测试DAO层

1. 环境配置

  • Springboot 2.7.8
  • h2 2.1.214

2. POM文件

  • 引入springboot parent pom
点击查看代码
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.7.8</version>
  <relativePath/>
</parent>
  • 引入junit , springboot-test, spring-data-jpa, H2
点击查看代码
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>
	
	<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
	</dependency>
	
	<dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
	</dependency>

3. H2配置

H2是一款内存数据库,可以配合单测测试数据层。实现原理是将依赖的三方数据库通过内存的方式进行mock。其中H2数据库的数据表结构以及数据可以通过sql脚本文件初始化,也可以在代码中增删数据。

test/resources/h2conf.properties
#使用h2数据库
spring.datasource.url=jdbc:h2:mem:test;MODE=Oracle;
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver

spring.sql.init.platform=h2
#数据初始化脚本地址
spring.sql.init.schema-locations=classpath:script/schema-h2.sql
# jpa配置
spring.jpa.database=h2
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=false
spring.jpa.open-in-view=true

spring.main.banner-mode=off


在 test/resources/script 下创建schema-h2.sql,内容为建表语句。

4. 编写单测代码

使用 @DataJpaTest 测试spring-data-jpa 框架下的数据层,@TestPropertySource 引入指定配置文件, @ContextConfiguration 引入springboot上下文。

点击查看代码
@DataJpaTest
@ContextConfiguration(classes=Application.class)
@TestPropertySource(locations = {"classpath:h2conf.properties"})
public class ServiceImplDaoTest {

    private SomeServiceImpl service;
    @Autowired
    private SomeRepository repository;
    @Autowired
    private TestEntityManager entityManager;

    @BeforeEach
    public  void setUp() {
        service = new SomeServiceImpl();
        ReflectionTestUtils.setField(service, "repository", repository);

    }
    @Test
    public void testSelect() {
        insertData();
        List<SomeEntity> all = 	service.findAll();
        Assertions.assertEquals(10, all.size());
    }

    /**
     * for test sql
     */
    public void insertData() {
        // mock 10 data
        for (int i = 0; i < 10; i++) {
            SomeEntity entity = new SomeEntity();
            entityManager.persist(entity);
        }
    }

}
posted @ 2023-06-04 18:27  我的南珠里  阅读(495)  评论(0编辑  收藏  举报