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);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/554262.html
標籤:其他
上一篇:C++面試八股文:struct、class和union有哪些區別?
下一篇:返回列表