Junit写法及与spring整合过程详解
更新时间:2020年06月19日 15:37:22 作者:64Byte
这篇文章主要介绍了Junit写法及与spring整合过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
junit之前的写法:
//在Before中注入service类
private IUserService userService;
@Before
public void setUp() throws Exception {
//使用xml的方式
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//使用注解的方式
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
userService = applicationContext.getBean(IUserService.class);
}
Spring与junit整合:
不需要手动创建Spring容器, 自动把bean注入到测试类
1、导入spring-test的依赖, 需要junit
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.3.RELEASE</version> </dependency>
2、在测试类使用spring-test的注解
@RunWith(class)
@ContextConfiguration(指定配置文件)
//测试类运行的环境,在spring环境下运行,在测试类, 注入Spring容器的bean
@RunWith(SpringJUnit4ClassRunner.class)
//在创建spring容器时,指定加载哪个配置文件 - - 相当于之前的手动获取对象
@ContextConfiguration("classpath:applicationContext.xml")
public class UserServiceImplTest {
@Autowired //注入IUserService
private IUserService userService;
@Test
public void testFindUserById() {
userService.findUserById(2);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Springboot如何使用Aspectj实现AOP面向切面编程
这篇文章主要介绍了Springboot如何使用Aspectj实现AOP面向切面编程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01
Java如何使用ConfigurationProperties获取yml中的配置
这篇文章主要介绍了Java如何使用ConfigurationProperties获取yml中的配置,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-02-02
详解基于java的Socket聊天程序——服务端(附demo)
这篇文章主要介绍了详解基于java的Socket聊天程序——服务端(附demo),具有一定的参考价值,感兴趣的小伙伴们可以参考一下。2016-12-12


最新评论