Spring Boot 基于 JUnit 5 实现单元测试

简介: Spring Boot 基于 JUnit 5 实现单元测试

简介

 

Spring Boot 2.2.0 版本开始引入 JUnit 5 作为单元测试默认库,在 Spring Boot 2.2.0 版本之前,spring-boot-starter-test 包含了 JUnit 4 的依赖,Spring Boot 2.2.0 版本之后替换成了 Junit Jupiter。

 

JUnit 4 和 JUnit 5 的差异

 

1. 忽略测试用例执行

 

JUnit 4:

 

@Test
@Ignore
public void testMethod() {
   // ...
}

 

JUnit 5:

 

@Test
@Disabled("explanation")
public void testMethod() {
   // ...
}

 

2. RunWith 配置

 

JUnit 4:

 

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    @Test
    public void contextLoads() {
    }
}

 

JUnit 5:

 

@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ApplicationTests {
    @Test
    public void contextLoads() {
    }
}

 

3. @Before、@BeforeClass、@After、@AfterClass 被替换

 

  • @BeforeEach 替换 @Before
  • @BeforeAll 替换 @BeforeClass
  • @AfterEach 替换 @After
  • @AfterAll 替换 @AfterClass

 

开发环境

 

  • JDK 8

 

示例

 

1.创建 Spring Boot 工程。

 

2.添加 spring-boot-starter-web 依赖,最终 pom.xml 如下。

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>tutorial.spring.boot</groupId>
    <artifactId>spring-boot-junit5</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-junit5</name>
    <description>Demo project for Spring Boot Unit Test with JUnit 5</description>
 
    <properties>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

 

3.工程创建好之后自动生成了一个测试类。

 

package tutorial.spring.boot.junit5;
 
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
 
@SpringBootTest
class SpringBootJunit5ApplicationTests {
 
    @Test
    void contextLoads() {
    }
 
}

 

这个测试类的作用是检查应用程序上下文是否可正常启动。

 

@SpringBootTest 注解告诉 Spring Boot 查找带 @SpringBootApplication 注解的主配置类,并使用该类启动 Spring

应用程序上下文。

 

4.补充待测试应用逻辑代码

 

4.1. 定义 Service 层接口

 

package tutorial.spring.boot.junit5.service;
 
public interface HelloService {
 
    String hello(String name);
}

 

4.2. 定义 Controller 层

 

package tutorial.spring.boot.junit5.controller;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import tutorial.spring.boot.junit5.service.HelloService;
 
@RestController
public class HelloController {
 
    private final HelloService helloService;
 
    public HelloController(HelloService helloService) {
        this.helloService = helloService;
    }
 
    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name) {
        return helloService.hello(name);
    }
}

 

4.3. 定义 Service 层实现

 

package tutorial.spring.boot.junit5.service.impl;
 
import org.springframework.stereotype.Service;
import tutorial.spring.boot.junit5.service.HelloService;
 
@Service
public class HelloServiceImpl implements HelloService {
 
    @Override
    public String hello(String name) {
        return "Hello, " + name;
    }
}

 

5.编写发送 HTTP 请求的单元测试。

 

package tutorial.spring.boot.junit5;
 
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
 
    @LocalServerPort
    private int port;
 
    @Autowired
    private TestRestTemplate restTemplate;
 
    @Test
    public void testHello() {
        String requestResult = this.restTemplate.getForObject("http://127.0.0.1:" + port + "/hello/spring",
                String.class);
        Assertions.assertThat(requestResult).contains("Hello, spring");
    }
}

 

说明:

 

  • webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT 使用本地的一个随机端口启动服务;
  • @LocalServerPort 相当于 @Value("${local.server.port}");
  • 在配置了 webEnvironment 后,Spring Boot 会自动提供一个 TestRestTemplate 实例,可用于发送 HTTP 请求。
  • 除了使用 TestRestTemplate 实例发送 HTTP 请求外,还可以借助 org.springframework.test.web.servlet.MockMvc 完成类似功能,代码如下:
package tutorial.spring.boot.junit5.controller;
 
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
 
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
 
    @Autowired
    private HelloController helloController;
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void testNotNull() {
        Assertions.assertThat(helloController).isNotNull();
    }
 
    @Test
    public void testHello() throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/spring"))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Hello, spring"));
    }
}

 

以上测试方法属于整体测试,即将应用上下文全都启动起来,还有一种分层测试方法,譬如仅测试 Controller 层。

 

6.分层测试。

 

 

package tutorial.spring.boot.junit5.controller;
 
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import tutorial.spring.boot.junit5.service.HelloService;
 
@WebMvcTest
public class HelloControllerTest {
 
    @Autowired
    private HelloController helloController;
 
    @Autowired
    private MockMvc mockMvc;
 
    @MockBean
    private HelloService helloService;
 
    @Test
    public void testNotNull() {
        Assertions.assertThat(helloController).isNotNull();
    }
 
    @Test
    public void testHello() throws Exception {
        Mockito.when(helloService.hello(Mockito.anyString())).thenReturn("Mock hello");
        this.mockMvc.perform(MockMvcRequestBuilders.get("/hello/spring"))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("Mock hello"));
    }
}

 

说明:

 

@WebMvcTest 注释告诉 Spring Boot 仅实例化 Controller 层,而不去实例化整体上下文,还可以进一步指定仅实例化 Controller 层的某个实例:@WebMvcTest(HelloController.class);

 

因为只实例化了 Controller 层,所以依赖的 Service 层实例需要通过 @MockBean 创建,并通过 Mockito 的方法指定 Mock 出来的 Service 层实例在特定情况下方法调用时的返回结果。

相关文章
|
10月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1104 0
|
6月前
|
安全 Java 测试技术
《深入理解Spring》单元测试——高质量代码的守护神
Spring测试框架提供全面的单元与集成测试支持,通过`@SpringBootTest`、`@WebMvcTest`等注解实现分层测试,结合Mockito、Testcontainers和Jacoco,保障代码质量,提升开发效率与系统稳定性。
|
6月前
|
Java 测试技术 数据库连接
【SpringBoot(四)】还不懂文件上传?JUnit使用?本文带你了解SpringBoot的文件上传、异常处理、组件注入等知识!并且带你领悟JUnit单元测试的使用!
Spring专栏第四章,本文带你上手 SpringBoot 的文件上传、异常处理、组件注入等功能 并且为你演示Junit5的基础上手体验
1068 3
|
Java 测试技术 开发者
必学!Spring Boot 单元测试、Mock 与 TestContainer 的高效使用技巧
【10月更文挑战第18天】 在现代软件开发中,单元测试是保证代码质量的重要手段。Spring Boot提供了强大的测试支持,使得编写和运行测试变得更加简单和高效。本文将深入探讨Spring Boot的单元测试、Mock技术以及TestContainer的高效使用技巧,帮助开发者提升测试效率和代码质量。
1386 2
|
10月前
|
安全 Java 测试技术
说一说 Spring Security 中的单元测试
我是小假 期待与你的下一次相遇 ~
195 1
|
10月前
|
Java 测试技术 数据库
说一说 SpringBoot 整合 Junit5 常用注解
我是小假 期待与你的下一次相遇 ~
142 1
|
测试技术 Java Spring
Spring 框架中的测试之道:揭秘单元测试与集成测试的双重保障,你的应用真的安全了吗?
【8月更文挑战第31天】本文以问答形式深入探讨了Spring框架中的测试策略,包括单元测试与集成测试的有效编写方法,及其对提升代码质量和可靠性的重要性。通过具体示例,展示了如何使用`@MockBean`、`@SpringBootTest`等注解来进行服务和控制器的测试,同时介绍了Spring Boot提供的测试工具,如`@DataJpaTest`,以简化数据库测试流程。合理运用这些测试策略和工具,将助力开发者构建更为稳健的软件系统。
258 0
|
XML Java 测试技术
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
这篇文章介绍了Spring5框架的三个新特性:支持@Nullable注解以明确方法返回、参数和属性值可以为空;引入函数式风格的GenericApplicationContext进行对象注册和管理;以及如何整合JUnit5进行单元测试,同时讨论了JUnit4与JUnit5的整合方法,并提出了关于配置文件加载的疑问。
Spring5入门到实战------17、Spring5新功能 --Nullable注解和函数式注册对象。整合JUnit5单元测试框架
|
Java 测试技术 Maven
Spring整合JUnit实现单元测试
本文介绍了如何在Java开发中使用Spring与JUnit进行单元测试。首先,设置JUnit和Spring环境,创建待测试的业务逻辑类,如MyService。接着,编写JUnit测试类MyServiceTest,使用`@RunWith(SpringJUnit4ClassRunner.class)`和`@ContextConfiguration`注解,注入并测试MyService的方法。此外,借助Mockito模拟依赖对象,以及使用Spring TestContext框架进行集成测试,确保测试的隔离性和环境的稳定性。通过这些方法,可以提升代码质量和测试效率。
386 1
|
JSON Java 测试技术
Spring Boot中使用JUnit5进行单元测试
Spring Boot中使用JUnit5进行单元测试
1088 0
Spring Boot中使用JUnit5进行单元测试
下一篇
开通oss服务