Springboot项目整合junit4和junit5

1.springboot整合junit4
①依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

使用
@RunWith就是一个运行器 有两个 runner 可以选择,分别是 SpringRunner 和 SpringJUnit4ClassRunner。
如果是在 4.3 之前,只能选择 SpringJUnit4ClassRunner,如果是 4.3 之后,建议选择 SpringRunner。
SpringRunner 对 junit 的版本有要求,需要 4.12 及以上。

package com.springlog;

import com.springtest.SpringBootGatewayApplication;
import com.springtest.service.TestService;
import org.junit.Test; // 注意包路径
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

@RunWith(SpringRunner.class) // junit4需要配置runwith
@SpringBootTest(classes = SpringBootGatewayApplication.class) // 指定项目启动类以防报错找不到注入的类
public class TestJunitFour {
    
    

    @Resource
    TestService testService;

    @Test
    public void setTestService() {
    
    
        testService.testService("小江");
    }
}

2.springboot整合junit5
①依赖

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>

使用
@SpringBootTest(classes = SpringBootGatewayApplication.class)

package com.springlog;

import com.springtest.SpringBootGatewayApplication;
import com.springtest.service.TestService;
import org.junit.jupiter.api.Test; // 注意注解jupiter包
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest(classes = SpringBootGatewayApplication.class) // junit5只需引入此·注解即可
public class SpringBootGatewayApplicationTests {
    
    
    @Resource
    TestService testService;

    @Test
    public void setTestService() {
    
    
	    Assertions.assertEquals(1, 1);
        testService.testService("小明");
        System.out.println("test");
    }
}

@SpringBootTest注解可以用来标记一个测试类,告诉Spring Boot启动一个完整的应用程序上下文,而不仅仅是一个单一的测试类或测试方法。将包含所有的Spring Bean、配置和依赖项,和应用程序中正常启动一样

猜你喜欢

转载自blog.csdn.net/weixin_43795840/article/details/129715476