首页 > 编程语言 > 详细

spring-boot-starter-test单元测试引入SpringRunner失败问题

时间:2019-12-11 15:48:59      阅读:1719      评论:0      收藏:0      [点我收藏+]

Spring Boot新版本默认使用Junit5,pom依赖为:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

同时,测试类的Demo如下,其中@SpringBootTest表示将该类作为Spring的测试类,加载到spring容器中,必不可少。

import static org.junit.jupiter.api.Assertions.assertEquals;

import example.util.Calculator;

import org.junit.jupiter.api.Test;

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class MyFirstJUnitJupiterTests {

    private final Calculator calculator = new Calculator();

    @Test
    void addition() {
        assertEquals(2, calculator.add(1, 1));
    }

}

 

 

如果项目中要使用旧版的Junit4,那么在pom文件中要删除掉“<exclusions>”这个对旧版本的支持,同时导入Junit4的相关依赖

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

在测试类中,不要忘了添加@Runwith(SpringRunner.class)注解,有时候@Test的导入的包也有影响,需要注意

 

文档:

Spring Boot:https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/html/spring-boot-features.html#boot-features-testing

Junit5:https://junit.org/junit5/docs/current/user-guide/#writing-tests

spring-boot-starter-test单元测试引入SpringRunner失败问题

原文:https://www.cnblogs.com/heyboom/p/12022750.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!