项目采用mybatis + spring开发,这是以前的测试代码, 【运行需要30s】
private static MemberService memberService; @BeforeClass public static void setUp() throws Exception{ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); memberService = (MemberService)context.getBean("memberService");
这种方式的不好,要实例化整个spring容器,如果项目很大,一个单元测试运行的时间将会很长;
下面我把myBatis从spring进行分离,分离后进行单元测试速度很快:下面是改进后的测试类,【运行只需3s】
private static MemberService memberService; @BeforeClass public static void setUp() throws Exception{ MemberDao memberDao = new MemberDao(); memberDao.setMemberMapper((MemberMapper)SessionFactory.getMapper(MemberMapper.class)); MemberServiceImpl memberServiceimpl = new MemberServiceImpl(); memberServiceimpl.setMemberDao(memberDao); memberService = memberServiceimpl;
1,configuration xml
2, TransactionManager类 自定义事务管理,主要是用作自动提交,autoCommit
public class TransactionManager implements TransactionFactory { @Override public Transaction newTransaction(Connection conn, boolean autoCommit) { Transaction tx = new JdbcTransaction(conn, true); return tx; } @Override public void setProperties(Properties arg0) { } }
3,下面是我的核心类 ,主要是获取sqlSession与Mapper接口
public class SessionFactory { private static SqlSessionFactory sessionFactory; private SessionFactory(){ } static{ String resource = "com/***/project/utils/mybatis.xml"; Reader reader; try { reader = Resources.getResourceAsReader(resource); sessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sessionFactory.openSession(); } public static Object getMapper(Class cls){ return MapperProxy.newMapperProxy(cls, getSqlSession()); } }
小结:把dao层分离可以进行快速的单元测试(严格来说是集成测试),但如果自动化运行所有的测试,也可以直接从spring容器中获取service进行测试,可参昭我的文章http://mingliang-luo.iteye.com/blog/1237351