Junit写法及与spring整合过程详解
时间:2021-01-15 11:15:39|栏目:JAVA代码|点击: 次
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);
}


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




