Spring Boot中进行Junit测试

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

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