Mybatis + Junit 单元测试
Posted 笑虾
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis + Junit 单元测试相关的知识,希望对你有一定的参考价值。
Mybatis + Junit 单元测试
Mybatis配置文件
src/main/resources/mybatis/mybatis-config-test.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="callSettersOnNulls" value="true" />
<setting name="returnInstanceForEmptyRow" value="true"/>
<setting name="cacheEnabled" value="true" /> <!-- 全局映射器启用缓存 -->
<setting name="useGeneratedKeys" value="true" /> <!-- 允许 JDBC 支持自动生成主键 -->
<setting name="defaultExecutorType" value="REUSE" /> <!-- 配置默认的执行器 -->
<setting name="logImpl" value="STDOUT_LOGGING" /> <!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 驼峰式命名 -->
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/zcpt?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8"/>
<property name="username" value="jerry"/>
<property name="password" value="jerry"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/testMapper.xml"/>
</mappers>
</configuration>
Junit
@Slf4j
public class TestMapperTest
@Resource
private TestMapper testMapper;
@Before
public void setUp() throws Exception
String resource = "mybatis/mybatis-config-test.xml";
InputStream stream =Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
//获取会话
SqlSession sqlSession = sqlSessionFactory.openSession();
//通过接口获取对象实例
testMapper = sqlSession.getMapper(TestMapper.class);
@Test
public void queryById()
Hero hero = testMapper.queryById(1L);
Assert.notNull(hero );
log.info("\\n================== queryById ==================");
log.info(JSONObject.toJSONString(hero , SerializerFeature.PrettyFormat));
以上是关于Mybatis + Junit 单元测试的主要内容,如果未能解决你的问题,请参考以下文章
mybatis 通过配置父类数据源连接和关闭数据,进行junit单元测试
MyBatis和SpringMVC集成事务在Junit测试下有效但是在实际项目无效的问题
SpringBoot2——数据访问的集成 & 单元测试(JUnit5)