1.原理是在Junit启动时加载SpringIoC容器
2.SpringIoC容器要根据Spring的配置文件加载
[示例代码]
package org.azcode.dao; import org.azcode.entity.Seckill; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.Date; import java.util.List; import static org.junit.Assert.*; /** * IDEA生成测试类的快捷键 Ctrl+Shift+T * 配置Spring和Junit的整合,Junit启动时加载SpringIoC容器 * Spring-test,junit * Created by azcod on 2017/4/14. */ @RunWith(SpringJUnit4ClassRunner.class) //告诉junit Spring配置文件的位置 @ContextConfiguration({"classpath:spring/spring-dao.xml"}) public class SeckillDaoTest { //注入Dao实现类 @Resource private SeckillDao seckillDao; @Test public void queryById() throws Exception { long id = 1000; Seckill seckill = seckillDao.queryById(id); System.out.println(seckill.getName()); System.out.println(seckill); /* 1000元秒杀iphone7s Seckill{seckillId=1000, name='1000元秒杀iphone7s', number=100, startTime=Fri Apr 14 00:00:00 CST 2017, endTime=Sat Apr 15 00:00:00 CST 2017, createTime=Thu Apr 13 21:14:06 CST 2017} */ } @Test public void queryAll() throws Exception { /** * Caused by: org.apache.ibatis.binding.BindingException: * Parameter 'offset' not found. Available parameters are [0, 1, param1, param2] */ // java没有保存形参的记录:queryAll(int offset, int limit) -> queryAll(arg1,arg2) // 解决方式:通过@Param("paramName")注释告诉mybatis sql中对应的参数是哪一个 List<Seckill> seckills = seckillDao.queryAll(0,10); for(Seckill seckill: seckills){ System.out.println(seckill); } } @Test public void reduceNumber() throws Exception { /** 09:23:58.681 [main] DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@4362d7df] will not be managed by Spring 09:23:58.687 [main] DEBUG o.azcode.dao.SeckillDao.reduceNumber - ==> Preparing: update seckill set number = number -1 where seckill_id = ? and start_time <= ? and end_time >= ? and number > 0 09:23:58.734 [main] DEBUG o.azcode.dao.SeckillDao.reduceNumber - ==> Parameters: 1000(Long), 2017-04-14 09:23:58.279(Timestamp), 2017-04-14 09:23:58.279(Timestamp) 09:23:58.739 [main] DEBUG o.azcode.dao.SeckillDao.reduceNumber - <== Updates: 1 09:23:58.740 [main] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@f713686] */ Date killTime = new Date(); int updateCount = seckillDao.reduceNumber(1000L,killTime); System.out.println(updateCount); } }