Junit写法及与spring整合过程详解
junit之前的写法:
//在Before中注入service类
privateIUserServiceuserService;
@Before
publicvoidsetUp()throwsException{
//使用xml的方式
ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml");
//使用注解的方式
ApplicationContextapplicationContext=newAnnotationConfigApplicationContext(SpringConfiguration.class);
userService=applicationContext.getBean(IUserService.class);
}
Spring与junit整合:
不需要手动创建Spring容器,自动把bean注入到测试类
1、导入spring-test的依赖,需要junit
org.springframework spring-test 4.3.3.RELEASE
2、在测试类使用spring-test的注解
@RunWith(class)
@ContextConfiguration(指定配置文件)
//测试类运行的环境,在spring环境下运行,在测试类,注入Spring容器的bean
@RunWith(SpringJUnit4ClassRunner.class)
//在创建spring容器时,指定加载哪个配置文件--相当于之前的手动获取对象
@ContextConfiguration("classpath:applicationContext.xml")
publicclassUserServiceImplTest{
@Autowired//注入IUserService
privateIUserServiceuserService;
@Test
publicvoidtestFindUserById(){
userService.findUserById(2);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短