1 Star 0 Fork 2

superboycxx / spring-test

forked from jahentao / spring-test 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

背景

部门逐渐规范代码质量,要求单元测试用例代码覆盖率要达到50%,所以最近大家渐渐养成了写单元测试用例的习惯。由于系统功能主要就 是增删改查,所以当大家的单元测试用例使用同一个数据库时发生数据冲突,经常造成单元测试不通过的情况,影响了代码进度。所以对于 每一个测试用例需要一个独立的数据库,这时候经过研究发现了h2内存数据库,解决了之前的问题。


H2数据库简介

h2是一个开源的内存数据库,支持在内存中创建数据库和表


Maven配置

<!--H2内存数据库,用于测试环境-->
<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
  <version>1.4.196</version>
  <scope>test</scope>
</dependency>


#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

初始化数据库

<!-- 初始化数据库 -->
<jdbc:initialize-database data-source="dataSource" ignore-failures="NONE">
    <!-- 初始化表结构 -->
    <jdbc:script location="classpath:test-schema.sql"/>
    <!--改用DbSetup在程序中初始化表数据-->
    <!--<jdbc:script location="classpath:test-data.sql"/>-->
</jdbc:initialize-database>

单元测试

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 {
    }
}

空文件

简介

Spring-Test + H2 + MyBatis + JUnit 整合-单元测试环境搭建 展开 收起
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/chenxingxing6/spring-test.git
git@gitee.com:chenxingxing6/spring-test.git
chenxingxing6
spring-test
spring-test
master

搜索帮助