带有Spring Boot 2的Junit 5

了解如何借助RestTemplateSpring boot 2应用程序的Junit 5中编写单元测试,以测试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.how2codex.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://how2codex.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.Assert断言,我们将使用org.junit.jupiter.api.Assertions类通过测试用例的实际输出来验证期望的输出。所有的JUnit Jupiter断言都是静态方法。

阅读更多:JUnit 5断言示例

2.3。Maven surefire插件

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

package com.how2codex.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.how2codex.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的问题。

学习愉快!

saigon has written 1440 articles

Leave a Reply