Spring 集成Junit

1,整合Junit4

maven引入spring-test 和 junit4

            
                org.springframework
                spring-test
                5.2.22.RELEASE
                        
            
                junit
                junit
                4.13
                test
            

2,在test目录下创建测试类

@RunWith(SpringJUnit4ClassRunner.class)  //启用Junit4
@ContextConfiguration("classpath:META-INF/context-junit.xml") //加载配置文件
public class SpringJunit4 {

    @Autowired
    private Machine machine;

    @Test
    public void test1() throws Exception {
        System.out.println(machine.getObject());
    }

}

2,整合Junit5

1,maven引入spring-test 和 junit5 

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

            
            
                org.junit.jupiter
                junit-jupiter
                5.8.2
                test
            

2,在test目录下创建测试类

@ExtendWith(SpringExtension.class) //启用Junit5
@ContextConfiguration("classpath:META-INF/context-junit.xml") //加载配置文件
public class SpringJunit5 {

    @Autowired
    private Machine machine;

    @Test
    public void test1() throws Exception {
        System.out.println(machine.getObject());
    }

}

说明:在spring5中,可以用复合注解  @SpringJUnitConfig(locations = {"classpath:META-INF/context-junit.xml"})  代替 @ExtendWith(SpringExtension.class) 和 @ContextConfiguration("classpath:META-INF/context-junit.xml")

//@ExtendWith(SpringExtension.class) //启用Junit5
//@ContextConfiguration("classpath:META-INF/context-junit.xml") //加载配置文件
@SpringJUnitConfig(locations = {"classpath:META-INF/context-junit.xml"})
public class SpringJunit5 {

    @Autowired
    private Machine machine;

    @Test
    public void test1() throws Exception {
        System.out.println(machine.getObject());
    }

}

你可能感兴趣的:(Spring,spring,单元测试)