# spring-test **Repository Path**: chenxingxing6/spring-test ## Basic Information - **Project Name**: spring-test - **Description**: Spring-Test + H2 + MyBatis + JUnit 整合-单元测试环境搭建 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 2 - **Created**: 2019-05-04 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 背景 部门逐渐规范代码质量,要求单元测试用例代码覆盖率要达到50%,所以最近大家渐渐养成了写单元测试用例的习惯。由于系统功能主要就 是增删改查,所以当大家的单元测试用例使用同一个数据库时发生数据冲突,经常造成单元测试不通过的情况,影响了代码进度。所以对于 每一个测试用例需要一个独立的数据库,这时候经过研究发现了h2内存数据库,解决了之前的问题。 --- ## H2数据库简介 h2是一个开源的内存数据库,支持在内存中创建数据库和表 --- ## Maven配置 ```html com.h2database h2 1.4.196 test #Database config dha.driver=org.h2.Driver dha.url=jdbc:h2:file:target/foobar;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATESCHEMA IF NOT EXISTS "public";LOCK_TIMEOUT=10000; dha.portNumber=3306 dha.schemaName=dha dha.userName=sa dha.dbPassword= dha.validationQuery=select 1 dha.maxActive=100 ``` --- ## 初始化数据库 ```xml ``` --- ## 单元测试 ```java package com.jahentao.springtest.test.dao; import com.jahentao.springtest.dao.OrganizationDao; import com.jahentao.springtest.test.BaseTest; import com.ninja_squad.dbsetup.DbSetup; import com.ninja_squad.dbsetup.Operations; import com.ninja_squad.dbsetup.destination.DataSourceDestination; import com.ninja_squad.dbsetup.operation.Operation; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import javax.sql.DataSource; import static org.junit.Assert.assertNotNull; public class OrganizationDaoTest extends BaseTest { @Autowired private OrganizationDao dao; @Autowired private DataSource dataSource; @Before public void setUp() throws Exception { Operation operation = Operations.sequenceOf( Operations.deleteAllFrom("sys_organization"), Operations.insertInto("sys_organization") .columns("name","priority","parent_id","parent_ids","available") .values("测试组", 10, 0, "0/", Boolean.TRUE) .build() ); DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation); dbSetupTracker.launchIfNecessary(dbSetup); } @Test public void testFindById() { assertNotNull(dao.findById(1L)); } @After public void tearDown() throws Exception { } } ```