spring整合junit集成测试

21 篇文章 0 订阅
之前测试代码: 
Java代码   收藏代码
  1. @Test  
  2.     public void testAddOld() {  
  3.         ApplicationContext appContext = new ClassPathXmlApplicationContext("application.xml");  
  4.         appContext.getBean("testTbService");  
  5.         TestTb testTb = new TestTb();  
  6.         testTb.setName("小虫");  
  7.         testTb.setBirthday(new Date());  
  8.   
  9.         testTbService.addTestTb(testTb);  
  10.     }  


之前测试service时都是先加载spring的主配置文件,然后getBean从IOC容器中得到service的实例再进行相应的测试。比较麻烦。 

Java代码   收藏代码
  1. package cn.smallbug;  
  2.   
  3. import java.util.Date;  
  4.   
  5. import javax.annotation.Resource;  
  6.   
  7. import org.junit.Test;  
  8. import org.junit.runner.RunWith;  
  9. import org.springframework.test.context.ContextConfiguration;  
  10. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  11.   
  12. import cn.smallbug.core.bean.TestTb;  
  13. import cn.smallbug.core.service.TestTbService;  
  14.   
  15. /** 
  16.  *  
  17.  * @timestamp Jan 31, 2016 11:27:24 PM 
  18.  * @author smallbug 
  19.  */  
  20. @RunWith(SpringJUnit4ClassRunner.class)  
  21. @ContextConfiguration(locations = { "classpath:application-context.xml" })  
  22. public class TestTestTb {  
  23.   
  24.     @Resource  
  25.     private TestTbService testTbService;  
  26.   
  27.     @Test  
  28.     public void testAdd() {  
  29.         TestTb testTb = new TestTb();  
  30.         testTb.setName("小虫");  
  31.         testTb.setBirthday(new Date());  
  32.   
  33.         testTbService.addTestTb(testTb);  
  34.     }  
  35. }  


殊不知其实是可以在类上加两行注解: 
Java代码   收藏代码
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations = { "classpath:application-context.xml" })  

再@Resource注入,直接就可以测试service了。而且可以再写个抽象类,加上上面两句注解,谁要测试直接继承这个类就行了,非常方便。 


转自:http://smallbug-vip.iteye.com/blog/2275529

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值