mybatis 通过配置父类数据源连接和关闭数据,进行junit单元测试

Posted 张氏码农之旅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis 通过配置父类数据源连接和关闭数据,进行junit单元测试相关的知识,希望对你有一定的参考价值。

来源:https://blog.csdn.net/Bigbig_lyx/article/details/80646005

解决问题,单元测试没经过单独配置,每个测试方法中要添加配置数据源

 

一:配置父类

import java.io.IOException;
import java.io.Reader;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;

/**
 * 提供配置数据源连接和关闭数据连接
 */
public class BaseMapper {
    
    private static SqlSessionFactory sqlSessionFactory;
    @BeforeClass
    public static void init(){
        try{
            Reader reader=Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        }catch(IOException ignore){
            ignore.printStackTrace();
        }
    }
    
    public SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
 
}

一:新建单元测试类UserMapperTestEx.java,继承自测试基类BaseMapperTest.java

package tk.mybatis.simple.mapper;
 
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
 
import junit.framework.Assert;
import tk.mybatis.simple.model.SysRole;
import tk.mybatis.simple.model.SysUser;
 
public class UserMapperTestEx extends BaseMapperTest{
    
    @Test
    public void  testSelectById(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            SysUser user = userMapper.selectById(1l);
            printCountryList(user);
        } finally {
            // TODO: handle finally clause
            sqlSession.close();
        }
    }
 
    private void printCountryList(SysUser user){
            System.out.printf("%-4d%4s%4s
",
                    user.getId(),
                    user.getUserEmail(),
                    user.getUserPassword(),
                    user.getUserEmail(),
                    user.getUserInfo(),
                    user.getHeadImg(),
                    user.getCreateTime()
                    );
    }
 
    @Test
    public void  selectById(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            SysUser user = userMapper.selectById(1l);
            Assert.assertNotNull(user);
            Assert.assertEquals("admin", user.getUserName());
        } finally {
            // TODO: handle finally clause
            sqlSession.close();
        }
    }
    
    @Test
    public void  selectByAll(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            List<SysUser> userList = userMapper.selectAll();
            Assert.assertNotNull(userList);
            Assert.assertTrue(userList.size()>0);
        } finally {
            // TODO: handle finally clause
            sqlSession.close();
        }
    }
    
    @Test
    public void  selectRolesByUserId1(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            List<SysRole> roleList = userMapper.selectRolesByUserId1(1l);
            Assert.assertNotNull(roleList);
            for(SysRole role:roleList){
                System.out.println(role.toString1());
            }
        } finally {
            // TODO: handle finally clause
            sqlSession.close();
        }
    }
    
    @Test
    public void  selectRolesByUserId2(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            List<SysRole> roleList = userMapper.selectRolesByUserId2(1l);
            for(SysRole role:roleList){
                System.out.println(role.toString2());
            }
        } finally {
            // TODO: handle finally clause
            sqlSession.close();
        }
    }
    
    @Test
    public void  insert(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            SysUser user=new SysUser();
            user.setUserName("liuyx");
            user.setUserPassword("eazytec@123");
            user.setUserEmail("liuyexiang@byosoft.com.cn");
            user.setUserInfo("liuyx info");
            user.setHeadImg(new byte[]{1,2,3,4,5,6,7,8,9,0});
            user.setCreateTime(new Date());
            int result=userMapper.insert(user);
            Assert.assertEquals(1, result);
            Assert.assertNull(user.getId());
        } finally {
            // TODO: handle finally clause
            //为了不影响其他操作,设置为回滚,数据库自增长序列仍在进行,
            //默认的sqlSessionFactory.openSession()是不自动提交的
            //不手动执行commit就不会提交到数据库中
            //sqlSession.rollback();
            sqlSession.commit();
            sqlSession.close();
        }
    }
    
    @Test
    public void  insert2(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            SysUser user=new SysUser();
            user.setUserName("liuyx");
            user.setUserPassword("eazytec@123");
            user.setUserEmail("liuyexiang@byosoft.com.cn");
            user.setUserInfo("liuyx info");
            user.setHeadImg(new byte[]{1,2,3,4,5,6,7,8,9,0});
            user.setCreateTime(new Date());
            int result=userMapper.insert2(user);
            Assert.assertEquals(1, result);
            Assert.assertNotNull(user.getId());
        } finally {
            // TODO: handle finally clause
            //sqlSession.rollback();
            sqlSession.commit();
            sqlSession.close();
        }
    }
    
    @Test
    public void update(){
        SqlSession sqlSession=getSqlSession();
        
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            SysUser user = userMapper.selectById(1001l);
            System.out.println("获取id为1001的用户userName,更新前为:" + user.getUserName());
            user.setUserName("test" + new Date().toString());
            user.setUserEmail("test@byosoft.com.cn");
            int result = userMapper.updateById(user);
            user = userMapper.selectById(user.getId());
            System.out.println("获取id为1001的用户userName为,更新后为:" + user.getUserName());
        } finally {
            // TODO: handle finally clause
            sqlSession.commit();
            sqlSession.close();
        }
    }
    
    @Test
    public void delete(){
        SqlSession sqlSession=getSqlSession();
        
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            //int result = userMapper.deleteById(1003l);
            int result2=userMapper.deleteByUser(userMapper.selectById(1004l));
        } finally {
            // TODO: handle finally clause
            sqlSession.commit();
            sqlSession.close();
        }
    }
    
    /**
     * 多参数sql
     */
    @Test
    public void  selectRolesByUserIdAndRoleEnabled(){
        
        SqlSession sqlSession=getSqlSession();
        try {
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            List<SysRole> roleList = userMapper.selectRolesByUserIdAndRoleEnabled(1l, 1,"admin","test");
            for(SysRole role:roleList){
                System.out.println(role.toString1());
            }
        } finally {
            // TODO: handle finally clause
            sqlSession.close();
        }
    }
    
    /**
     * 简单实现动态代理
     */
    @Test
    public void testProxy(){
        SqlSession sqlSession=getSqlSession();
        MyMapperProxy userMapperProxy=new MyMapperProxy(UserMapper.class, sqlSession);
        UserMapper userMapper=(UserMapper) Proxy.newProxyInstance(
                Thread.currentThread().getContextClassLoader(),
                new Class[] {UserMapper.class},
                userMapperProxy
        );
        System.out.println("testProxy");
        List<SysUser> user=userMapper.selectAll();
    }
}

 

以上是关于mybatis 通过配置父类数据源连接和关闭数据,进行junit单元测试的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis_01

优秀的持久层框架-Mybatis框架解析

五分钟学会Mybatis通过Mapper代理连接数据库

MyBatis核心配置文件概述

mybatis 是在啥时候连接到数据库的,是在服务器启动时连接还是执行sql语句时候连接?

mybatis通过windows方式连接sqlserver数据库配置文件怎么写?