Spring (5) integration Junit

Spring integrates Junit

Why integrate Junit
in the test? In order to reduce the redundancy of the code, we usually extract the common part, but for a staff who specializes in testing, this part does not belong to his consideration.
And in Junit, it does not care whether we use the Spring framework or not. When executing the test method, junit does not know whether we are using the spring framework, so it will not read the configuration file/configuration class for us to create Spring core container.
Therefore, when the test method is executed in junit, there is no Ioc container, even if the Autowired annotation is written, the injection cannot be realized.

How to achieve integration

Step1: Import the junit jar package integrated by spring

 <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: Use an annotation @Runwith provided by junit to replace the original main method with the main method provided by spring

Step3: Tell the spring runner, whether spring and ioc creation is based on xml or annotation, and explain the location

@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);
    }
}

After the integration is complete, for testers, they only need to write the content in @Test, regardless of whether the framework is used

Guess you like

Origin blog.csdn.net/weixin_45925906/article/details/112795137