带有 Spring boot 2 的 Junit 5

位置:首页>文章>详情   分类: Java教程 > 编程技术   阅读(309)   2023-06-26 07:54:18

的帮助下学习在 Spring boot 2 应用程序中使用 Junit 5 编写单元测试RestTemplate,用于测试 REST API 或 spring mvc 应用程序。

1.Maven依赖

默认情况下,spring-boot-starter-test 依赖项将 junit 4 依赖项导入 Spring boot 应用程序。要使用 Junit 5,我们必须在项目依赖项中排除 Junit 4 并包含 Junit 5

我们正在使用最新的 spring boot 版本(迄今为止),即 2.1.7.RELEASE

<?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 
	http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.cundage.demo</groupId>
	<artifactId>springbootdemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>SpringBootDemo</name>
	<description>Spring Boot2 REST API Demo for http://cundage.com</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.7.RELEASE</version>
		<relativePath />
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<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>

			<!-- exclude junit 4 -->
			<exclusions>
				<exclusion>
					<groupId>junit</groupId>
					<artifactId>junit</artifactId>
				</exclusion>
			</exclusions>

		</dependency>

		<!-- junit 5 -->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-engine</artifactId>
			<scope>test</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2. 编写 Junit 5 测试

如果这是新应用程序,那么我们将编写新的单元测试,否则我们将更改代码以从 Junit 4 迁移到 Junit 5

2.1.移除@RunWith(SpringRunner.class)

使用 Junit 5,我们不再需要 @RunWith(SpringRunner.class)。 Spring 测试是用 @ExtendWith(SpringExtension.class)@SpringBootTest 执行的,其他 @…Test 注释已经用它注释了。

2.2.使用 Junit 5 断言

我们将使用 org.junit.jupiter.api.Assertions 类来使用测试用例的实际输出来验证预期输出,而不是使用 org.junit.Assert 进行断言。所有 JUnit Jupiter 断言都是静态方法。

更多参考:JUnit 5 断言示例

2.3. Maven surefire 插件

使用 maven 的 surefire 插件基于标签包含或排除测试,或配置测试运行时。 [链接]

package com.cundage.rest;

import java.net.URI;
import java.net.URISyntaxException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import com.cundage.rest.model.Employee;

//@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class SpringBootDemoApplicationTests 
{   
    @LocalServerPort
    int randomServerPort;
    
    @Test
    public void testAddEmployeeSuccess() throws URISyntaxException 
    {
        RestTemplate restTemplate = new RestTemplate();
        final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
        URI uri = new URI(baseUrl);
        Employee employee = new Employee(null, "Adam", "Gilly", "test@email.com");
        
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-COM-PERSIST", "true");      

        HttpEntity<Employee> request = new HttpEntity<>(employee, headers);
        
        ResponseEntity<String> result = restTemplate.postForEntity(uri, request, String.class);
        
        //Verify request succeed
        Assertions.assertEquals(201, result.getStatusCodeValue());
    }
    
    @Test
    public void testAddEmployeeMissingHeader() throws URISyntaxException 
    {
        RestTemplate restTemplate = new RestTemplate();
        final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
        URI uri = new URI(baseUrl);
        Employee employee = new Employee(null, "Adam", "Gilly", "test@email.com");
        
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<Employee> request = new HttpEntity<>(employee, headers);
        
        try 
        {
            restTemplate.postForEntity(uri, request, String.class);
            Assertions.fail();
        }
        catch(HttpClientErrorException ex) 
        {
            //Verify bad request and missing header
        	Assertions.assertEquals(400, ex.getRawStatusCode());
        	Assertions.assertEquals(true, ex.getResponseBodyAsString().contains("Missing request header"));
        }
    }

    @Test
    public void testGetEmployeeListSuccessWithHeaders() throws URISyntaxException 
    {
        RestTemplate restTemplate = new RestTemplate();
        
        final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
        URI uri = new URI(baseUrl);
        
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-COM-LOCATION", "USA");

        HttpEntity<Employee> requestEntity = new HttpEntity<>(null, headers);

        try 
        {
            restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            Assertions.fail();
        }
        catch(HttpClientErrorException ex) 
        {
            //Verify bad request and missing header
        	Assertions.assertEquals(400, ex.getRawStatusCode());
        	Assertions.assertEquals(true, ex.getResponseBodyAsString().contains("Missing request header"));
        }
    }
}

将您有关在 spring boot 2 应用程序中使用 junit 5 的问题交给我。

快乐学习!!

标签2: Spring Boot Test
地址:https://www.cundage.com/article/junit5-with-spring-boot2.html

相关阅读

在 的帮助下学习在 Spring boot 2 应用程序中使用 Junit 5 编写单元测试RestTemplate,用于测试 REST API 或 spring mvc 应用程序。 1.Mav...
学习使用 Spring TestRestTemplate 使用 HTTP POST REST API。在此后请求测试示例中,我们将发送请求正文和请求标头。 1.Maven依赖 确保您的项目中有 ...
学习使用 Spring boot 测试模块提供的 @RestClientTest 注解,它只关注使用 RestTemplateBuilder 或 RestTemplate 的 bean。 1、@...
了解 Spring Boot 提供的 @SpringBootTest 注解,以在单元测试或集成测试期间启用应用程序测试中的启动特定功能。 1. @SpringBootTest 我们可以在运行基于...
了解如何测试 Spring boot 网络应用程序。我们将看到一些非常快速的示例(使用 Junit 5)和配置: 验证应用程序已成功初始化 使用 @WebMvcTest 对 REST 控制器进行...
学习使用 @WebFluxTest 注释和 WebTestClient 单元测试 Spring boot webflux 控制器用于使用 Junit 5 测试 webflux 端点。 1. 使用...
学习Spring Boot有以下深度教程,涵盖从基本概念到打包、部署、监控等高级概念。 1. 开始 Spring Boot 简介 spring-boot-starter-parent 示例 sp...
为了在 spring boot 中安排作业 应用程序定期运行,spring boot 提供了 @EnableScheduling 和 @Scheduled 注释。让我们学习使用 Spring b...
学习使用 Spring Boot 和 Jersey 框架配置和创建 JAX-RS 2.0 REST API。此示例应用程序使用 Jersey 的 ServletContainer 来部署 RES...
学习编写 spring boot async rest controller,它支持异步请求处理并使用 Callable 接口返回响应。 1. spring boot异步控制器 编写控制器并让它...