## 1. 環境配置 - Springboot 2.7.8 - h2 2.1.214 ## 2. POM文件 - 引入springboot parent pom 點擊查看代碼 ``` org.springframework.boot spring-boot-starter-parent 2.7.8 ...
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);
}
}
}