spring04_spring整合Junit
1、问题和思路
在测试类中,当我们需要使用spring容器进行方法测试的时候,总是需要写下面两句。因为这两行代码获取了容器对象,没有他们就会产生空指针异常
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); IAccountService as = ac.getBean("accountService",IAccountService.class);
因此,如果程序可以自动帮助我们创建容器,我们不需要类似上面的手动创建,问题就解决了。
但是,Junit显然无法实现这个想法,因为Junit甚至都不知道我们是否使用了spring框架。对于这个问题,JUnit给我们暴露了一个注解,可以替换掉它原有的运行器。
Spring也提供了一个运行器,可以用来读取配置文件或者注解。这样的话我们只需要告诉这个运行器我们配置文件的路径就可以了。
2、配置步骤
1)spring和JUnit的整合jar包导入。这里需要注意的是,这里也需要spring的aop的jar包

2)替换Junit的运行器(使用@RunWith注解)
@RunWith(SpringJUnit4ClassRunner.class) public class AccountServiceTest { }
3)指定配置文件位置(使用@ContextCnofiguration注解 )
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:bean.xml"})
public class AccountServiceTest {
}
4)给测试类变量注入数据(使用@Autowired注解)
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations= {"classpath:bean.xml"}) public class AccountServiceTest { @Autowired private IAccountService as ; }
3、疑问:为什么不把测试类配置到xml中
首先要明确的是在xml中配置的方式是没有问题的。
但是不这样的原因是:
1)当我们在xml中配置了测试类对象,加载容器的时候就会创建对象
2)但是测试类只是我们用来测试功能的,实际项目中不需要它的参加,所以配置后创建了测试对象,但是并不使用。那么存放在容器中就会造成资源的浪费。
所以基于这两点,不会把测试对象配置在xml中。

浙公网安备 33010602011771号