zoukankan      html  css  js  c++  java
  • Spring整合Junit4

    1、加入相应依赖包

    junit4-4.7.jar 以及spring相关jar包

    2、在测试代码的源码包中如 src/test/java 新建一个抽象类如下

     1 import org.junit.runner.RunWith;
     2 import org.springframework.test.context.ContextConfiguration;
     3 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
     4 import org.springframework.test.context.transaction.TransactionConfiguration;
     5 import org.springframework.transaction.annotation.Transactional;
     6 /**
     7  * 所有测试类的基类
     8  */
     9 @RunWith(SpringJUnit4ClassRunner.class)
    10 /**
    11  * 多个配置文件以逗号隔开,如果配置文件在WEB-INF目录下可使用file进行配置具体如下
    12  * @ContextConfiguration(locations = {"classpath:applicationContext.xml","file:WebRoot/WEB-INF/config/applicationContext-*.xml"})
    13  */
    14 @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    15 /**
    16  * 用到事物管理时的配置,defaultRollback=true 表示执行完毕回滚
    17  */
    18 @Transactional
    19 @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
    20 public abstract class AbstractTestBase {
    21 }

    3、测试

     1 import org.junit.Test;
     2 import org.springframework.beans.factory.annotation.Autowired;
     3 
     4 import com.blog.model.User;
     5 
     6 public class UserServiceTest extends AbstractTestBase{
     7 
     8     @Autowired
     9     UserService userService;
    10 
    11     @Test
    12     public void testAdd(){
    13         User user = new User();
    14         user.setUsername("cyhe");
    15         user.setPassword("1234");
    16         boolean bool = userService.registerUser(user);
    17         if(bool == true){
    18             System.out.println("用户添加成功");
    19         } else {
    20             System.out.println("用户添加失败");
    21         }
    22     }
    23 }

    可以看到自动去加载相关的配置文件,最终显示添加成功

    作 者:创心coder
    QQ群:361982568
    订阅号:cxcoder
    文章不足之处,还请谅解!本文会不断完善更新,转载请保留出处。如果帮到了您,烦请点赞,以资鼓励。
  • 相关阅读:
    Windows 8 自带定时关机的4种实现方法
    Windows 7/8 自带定时关机命令
    将博客搬至CSDN
    【贪心】【POJ-3637】Shopaholic
    【贪心】【POJ-2437】Muddy roads
    【贪心】【POJ-1328&AOJ-195】Radar Installation
    【贪心】【POJ-1456】Supermarket
    【贪心】【HDOJ-1789】Doing Homework again
    【贪心】【POJ-1992】Ride to School
    【贪心】【POJ-1018】Communication System
  • 原文地址:https://www.cnblogs.com/cwane/p/5450162.html
Copyright © 2011-2022 走看看