学习新技能,针对Mybatis中Mapper的单元测试。
单元测试 – mapper层的单元测试
使用H2数据库进行单元测试
H2 数据库是一个开源的嵌入型内存数据库,采用纯Java语言实现;程序非常小巧轻便,整个完整的Jar包也只有1.5M左右,很容易集成到项目中。在自动化环境中可能需要大量模拟接口,包括数据存储接口,此时内存数据库是不二之选。本身作为嵌入式数据库并不需要额外的看护成本;在程序退出时,所有数据都能保证完全清除。
MAVEN依赖
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
<scope>test</scope>
</dependency>
application.properties(路径:test/resources)
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db_users;MODE=MYSQL;INIT=RUNSCRIPT FROM './src/test/resources/create_table.sql'
spring.datasource.username=
spring.datasource.password=
mybatis.configuration.map-underscore-to-camel-case=true
测试类
package com.puhuijia.dao.mapper;
import com.puhuijia.pojo.member.AreaBusiness;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
@RunWith(SpringRunner.class)
@MapperScan({"com.puhuijia.dao.mapper"})
@SpringBootTest(classes = {DataSourceAutoConfiguration.class, MybatisAutoConfiguration.class})
public class MembersMapperTest {
@Autowired
private AreaBusinessMapper mapper;
@Test
public void queryProvinceList() {
int row = mapper.deleteByPrimaryKey(1);
Assert.assertEquals(row, 0);
AreaBusiness areaBusiness = new AreaBusiness();
areaBusiness.setName("33333");
areaBusiness.setId(1);
areaBusiness.setCreateTime(new Date());
areaBusiness.setUpdateTime(new Date());
mapper.insertSelective(areaBusiness);
row = mapper.deleteByPrimaryKey(1);
Assert.assertEquals(row, 1);
}
}
create_table.sql
drop table if exists area_business;
CREATE TABLE `area_business` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '|20181106',
`name` varchar(50) NOT NULL DEFAULT '' COMMENT '|20181106',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '|20181106',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '|20181106',
PRIMARY KEY (`id`),
KEY `idx_create_time` (`create_time`),
KEY `idx_update_time` (`update_time`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COMMENT='333'
h2数据库
jdbc:h2:mem:DBName;DB_CLOSE_DELAY=-1
参数DB_CLOSE_DELAY是要求最后一个正在连接的连接断开后,不要关闭DB,因为下一个case可能还会有新连接进来。
H2与MySQL的一些常见区别
- 注释:不支持表级别的Comment
- 索引:H2中的索引是数据库内唯一,MySQL中的索引是每张表唯一
- CURRENT_TIMESTAMP: H2不支持记录更新时自动刷新字段时间,也就是不支持语句
ON UPDATE CURRENT_TIMESTAMP