Spring(五)之整合Junit

Spring整合Junit

为什么要整合Junit
在测试中,我们为了降低代码的冗余,通常会将公共部分进行抽离,但是对于一个专门测试的工作人员来说,这一部分并不属于他的考虑范畴。
并且在Junit中,它不会管我们是否采用了Spring框架,在执行测试方法时,junit根本不知道我们是不是使用了spring框架,所以也就不会为我们读取配置文件/配置类来创建spring核心容器。
所以,在junit中执行测试方法时,没有Ioc容器,就算写了Autowired注解,也无法实现注入。

如何实现整合

Step1:导入spring整合的junit的jar包

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
</dependency>

<--注意,此处的spring若是5版本以上,则junit要是4.12以上的版本-->

<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

Step2:使用junit提供的一个注解 @Runwith 把原来的main方法替换了,替换成spring提供的main方法

Step3:告知spring的运行器,spring和ioc创建是基于xml还是注解,并且说明位置

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class SpringTest {
    
    
    @Autowired
    IUserService is;

    @Test
    public void test1() throws Exception{
    
    
        List<User> users = is.queryAll();
        System.out.println(users);
    }
}

整合完成之后,对于测试人员来讲,就只需要写@Test里面的内容,而不用关心是否用了框架

猜你喜欢

转载自blog.csdn.net/weixin_45925906/article/details/112795137