Mybatis的基礎測試類

每當,咱們須要單元測試單個Mapper時,都須要將全部的Spring bean都加載一遍,致使單元測試時間過長。浪費開發時間,因此寫了個小demo。提高測試單個Mapper的測試速度。 代碼以下:java

import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.ClassPathResource;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 測試Mapper時,儘可能繼承該類。緣由加載速度快,不用額外再加載spring相關的內容
 * 
 * @author liurong
 *
 * @date 2019年1月10日
 */
public abstract class BaseMapper<T> {

	public T getMapper(Class<T> mapperClass, String mapperXml) throws Exception {
		// 數據源注入
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl("jdbc:mysql://192.168.32.138:3306/cumeeting?useUnicode=true&amp;characterEncoding=UTF-8");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setInitialSize(10);
		dataSource.setMinIdle(5);
		dataSource.setMaxActive(10);

		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis/mybatis_config.xml"));
		ClassPathResource classPathResource = new ClassPathResource("mybatis/mapper/" + mapperXml);
		ClassPathResource[] arr = { classPathResource };
		sqlSessionFactoryBean.setMapperLocations(arr);

		sqlSessionFactoryBean.setDataSource(dataSource);

		// 初始化
		sqlSessionFactoryBean.afterPropertiesSet();

		SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();

		Configuration configuration = sqlSessionFactory.getConfiguration();

		if (!configuration.hasMapper(mapperClass)) {
			configuration.addMapper(mapperClass);
		}

		T t = (T) configuration.getMapper(mapperClass, sqlSessionFactory.openSession());

		return t;
	}
}

實現類以下:mysql

import java.util.HashMap;

import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.fastonz.boss.mapper.IAgentMapper;
import com.fastonz.core.BaseMapper;

public class AgentMapperTest extends BaseMapper<IAgentMapper> {

	@Test
	public void test1() {
		try {
			IAgentMapper mapper = super.getMapper(IAgentMapper.class, "AgentMapper.xml");
			// 代用方法便可
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
相關文章
相關標籤/搜索