使用SpringJUnit4ClassRunner进行单元测试

Java代码   收藏代码
  1. import org.junit.Test;  
  2. import org.junit.runner.RunWith;  
  3. import org.springframework.test.context.ContextConfiguration;  
  4. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  5. import org.springframework.test.context.transaction.TransactionConfiguration;  
  6. import org.springframework.transaction.annotation.Transactional;  
  7.   
  8.   
  9. @RunWith(SpringJUnit4ClassRunner.class)  
  10. @ContextConfiguration(locations ={"classpath:/configuration/spring/beans.xml"})  
  11. @Transactional  
  12. @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)  
  13. public class TestModule{  
  14.     @Test  
  15.     public void testAdd() {  
  16.         try {  
  17.         dao.save(module);  
  18.         }catch(Exception e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.         }  
  22. }  

 这里需要对defaultRollback = true说明: true ? 测试数据不会污染数据库 : 会真正添加到数据库当中

当然这里不污染数据库只是在表中看不到数据, 但是如果你设置的主键是自动增长的话, 那么可以很明显得看出,虽然数据回滚了, 但是当你尝试不回滚新增数据到数据库的时候, 会发现ID不是连续的.所以并不是真正意义上的无污染

当然,这种方式也有他的好处,比单纯JUNIT要省去@before ,@after的方法.




实例:

package com.htbb.test;




import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;


@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ "classpath*:/spring.xml" })
public class ServiceTest {

    @Resource(name = "userService")
    UserService userService;

    private static final Logger LOGGER = Logger.getLogger(ServiceTest.class);
 
    @Test
    public void test(){
        
        List<UcUser> list = userService.list();
       
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值