美文网首页程序员
优雅单测-4如何优雅的做Mybatis单测

优雅单测-4如何优雅的做Mybatis单测

作者: uncle_hangzhou | 来源:发表于2020-06-30 15:30 被阅读0次

1.单元测试

单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。

所以数据层只应依赖数据层必须的配置即可,清爽干净、执行效率快

2.快速上手

2.1 依赖引入

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter-test</artifactId>
    <version>2.0.0</version>
</dependency>

2.2 增加单测(基于Spring容器的测试用例)

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = LiveReportMapperTest.Config.class)
public class LiveReportMapperTest {
    @Autowired
    private LiveReportMapper liveReportMapper;

    @Test
    public void getTest() {
        LiveReportPO liveReportPO = liveReportMapper.get(1L);
        Assert.assertNotNull(liveReportPO);
    }
    
    @Test
    public void listTest() {
        LiveReportParam liveReportParam = new LiveReportParam();
        liveReportParam.setLiveNo("712358906100218368");
        liveReportParam.setPageSize(10);
        liveReportParam.setPageStart(0);
        
        Assert.assertTrue(liveReportMapper.queryLiveReportList(liveReportParam).size() > 0);
    }
    
    @Configuration
    @Import(value = MybatisConfig.class)
    static class Config {
    }
}

liveReportMapper是自己的mybatis接口

MybatisConfig是数据层的数据源配置,内聚了数据源的连接信息、连接的技术框架

2.3 增加数据源配置依赖

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@MapperScan(basePackages = { "com.x.live.center.dao.mapper" }, 
            sqlSessionFactoryRef = "dataSessionFactory",
            sqlSessionTemplateRef = "dataSessionTemplate")
@PropertySource( "classpath:application-test.properties")
public class MybatisConfig {
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    
    @Bean(initMethod = "getConnection", destroyMethod = "close" ,name = "testDataSource")
    public DataSource dataSource() throws SQLException {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }  

    @Bean(name = "dataSessionFactory")
    public SqlSessionFactory sessionFactory(@Qualifier("testDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.x.live.center.dao.mapper");

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:/mapper/*Mapper.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "dataSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory dataSessionFactory) {
        return new SqlSessionTemplate(dataSessionFactory);
    }
}

通过@Configuration申明spring配置类:
1.DataSource为需要注册的数据源,这里使用HikariDataSource实现
2.SqlSessionFactory为sqlsession生产工厂实现
3.SqlSessionTemplate均为Mybatis-spring对应sqlsession实现
以上三项均为mybatis对DB操作的运行环境必须项

至此,mybatis单个单元测试完成,执行结果:

   ![image.png](https://img.haomeiwen.com/i23939366/c2cc75d4e4509851.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240 "image.png")

可以看到环境依赖了springboot环境,但是通过只依赖和加在mybatis相关配置,执行单测的效率相比直接启动springboot应用快非常多的

3.单元测试配置详解

3.1 单测case

RunWith: junit注解,表示使用spring-test包提供SpringRunner环境运行
ContextConfiguration:Spring环境相关配置
Import:导入Spring环境相关配置

3.2 数据层配置case

Configuration:为Spring容器中申明Bean的配置类
MapperScan:为Spring容器中扫描注册数据层接口的配置,指定接口路径
PropertySource:指定读取properties配置文件,一般存放环境变量
dataSource方法:为Spring返回需要注册的数据源,这里使用HikariDataSource实现
sessionFactory方法:SqlSessionFactory为sqlsession生产工厂实现
sqlSessionTemplate方法:SqlSessionTemplate均为Mybatis-spring对应sqlsession实现

相关文章

网友评论

    本文标题:优雅单测-4如何优雅的做Mybatis单测

    本文链接:https://www.haomeiwen.com/subject/vvsxqktx.html