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、配置和依赖项,和应用程序中正常启动一样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值