spice and wolfspice and wolf Be the One you wanna Be

Spring整合Junit

问题

在测试类中,每个测试方法都需要加一下两行代码:

ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
UserService service = context.getBean(UserService.class);

我们使用单元测试要测试的是业务问题,以上两段代码明显不是业务代码。

但是这两行代码的作用是获取容器,如果不写的话,会提示空指针异常,所以又不能轻易删掉。

解决方案

我们需要能自动帮我们创建容器的方法,junit暴露了一个@RunWith注解,可以让我们替换掉它的运行器。spring提供了运行器,我们现在只需要读取配置文件创建运行器就行了。

  1. 添加依赖。添加spring-test包即可
  2. 通过@RunWith注解,指定spring的运行器。spring的运行器是SpringJUnit4ClassRunner
  3. 通过@ContextConfiguration注解,指定spring运行器需要的配置文件
  4. 通过@Autowired给测试类中的变量注入数据
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestSpringJUnit {
    @Autowired
    private UserService service;
    
    public void save() {
        service.save();
    }
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Press ESC to close