平时工作中,DAO始终包含了或多或少的逻辑,即使能够通过功能测试来达到测试DAO的目的,但通过单元测试来测试DAO的实现是更有效的做法!
我们可能使用MySQL关系型数据库更多一些,但在实现单元测试时,需要一个更加独立的环境,也避免单元测试对实际数据库中的数据造成污染,因此在实现DAO单元测试时,我们使用H2内存数据库作为数据源。
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id bigint NOT NULL AUTO_INCREMENT COMMENT '自增id',
name varchar(20) NOT NULL COMMENT '姓名',
PRIMARY KEY (id)
) COMMENT='用户表';
INSERT INTO user (id, name)
VALUES (1, '张三'),
(2, '李四');
@ContextConfiguration(classes = {H2Config.class, MybatisConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class DaoBaseTest extends AbstractTestNGSpringContextTests {
}
@Configuration
@MapperScan(basePackages = "com.cw.dao.mapper")
@ComponentScan({"com.cw.dao"})
public class H2Config {
@Bean
public DataSource h2DataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql") // initialized the table statement
.addScript("classpath:data.sql")
.build();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// Load all SQL Mapper files
Resource[] mapperLocations = resolver.getResources("classpath:/mapper/*.xml");
sessionFactory.setMapperLocations(mapperLocations);
sessionFactory.setConfigLocation(resolver.getResources("classpath:mybatis-config.xml")[0]);
return sessionFactory.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
@Configuration
@ImportResource(locations = {"classpath:mybatis-config.xml"})
public class MybatisConfig {
@Bean
MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.cw.dao");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}
}
public class UserDaoTest extends DaoBaseTest {
List<User> users = userDao.queryAll();
assertEquals(2, users.size());
}
以上,是基于JUnit4、H2 实现的对MybatisMapper的单元测试,能够有效、及时的验证我们的DAO层实现是否正确。基于Junit5版本的单元测试实现将在后面更新。