Spring(五)----Spring框架整合JUnit单元测试

1. 为了简化了JUnit的测试,使用Spring框架也可以整合测试
2. 具体步骤
要求:必须先有JUnit的环境(即已经导入了JUnit4的开发环境)
步骤一:在程序中引入spring-test.jar
步骤二:在具体的测试类上添加注解

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration("classpath:applicationContext.xml")  
public class SpringDemo1 {  
  
    @Resource(name = "userService")  
    private UserService userService;  
  
    @Test  
    public void demo2() {  
        userService.save();  
    }  
} 
解释下用到的注解:
@RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境
@ContextConfiguration({"classpath:applicationContext.xml","classpath:spring/buyer/applicationContext-service.xml"}) 
导入配置文件,这里我的applicationContext配置文件是根据模块来分类的。如果有多个模块就引入多个“applicationContext-service.xml”文件。如果所有的都是写在“applicationContext.xml”中则这样导入: 
@ContextConfiguration(locations = "classpath:applicationContext.xml") 
我们也可以创建一个基类
@RunWith(SpringJUnit4ClassRunner.class)//使用junit4进行测试  
@ContextConfiguration("classpath:applicationContext.xml")//加载配置文件  
public class BaseJunit4Test {  
}  
然后,具体的测试类去继承这个基类
public class Demo extends BaseJunit4Test{  
  
    @Resource(name="userServiceImpl")  
    private UserService userService;  
  
    @Test  
    public void run1() {  
        userService.sayHello();  
    }  
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值