带有标题示例的Spring Boot TestRestTemplate POST

通过Spring TestRestTemplate学习使用HTTP POST REST API。在此请求后测试示例中,我们将发送请求正文以及请求标头。

1. Maven依赖

确保您的项目中具有spring-boot-starter-test依赖项,以便可以TestRestTemplate在运行时访问类。如果您使用的是@SpringBootTest注解,则a TestRestTemplate会自动可用并且可以@Autowired进入您的测试。

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

2. HTTP POST API

我们正在使用Spring boot 2 rest示例的代码库。POST API如下所示。

  1. 它将在雇员集合中添加一个雇员。
  2. 它接受Employee对象中的员工数据。
  3. 它接受并创建JSON meda类型。
  4. 它接受两个HTTP标头,即X-COM-PERSIST和X-COM-LOCATION。第一个标头是必需的,第二个标头是可选的。
  5. 它返回创建资源的位置。
package com.how2codex.rest.controller;

import java.net.URI;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import com.how2codex.rest.dao.EmployeeDAO;
import com.how2codex.rest.model.Employee;
import com.how2codex.rest.model.Employees;

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController 
{
    @Autowired
    private EmployeeDAO employeeDao;
     
    @PostMapping(path= "/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Object> addEmployee(
                        @RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
                        @RequestHeader(name = "X-COM-LOCATION", required = false, defaultValue = "ASIA") String headerLocation,
                        @RequestBody Employee employee) 
                 throws Exception 
    {       
        //Generate resource id
        Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
        employee.setId(id);
        
        //add resource
        employeeDao.addEmployee(employee);
        
        //Create resource location
        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                                    .path("/{id}")
                                    .buildAndExpand(employee.getId())
                                    .toUri();
        
        //Send location in response
        return ResponseEntity.created(location).build();
    }
}

我不会讨论其他类,因为它与rest api测试无关。您可以下载源代码并查看以了解更多信息。

3. Spring TestRestTemplate

为了测试POST API,我们需要创建带有@SpringBootTest注解的spring boot测试类。

package com.how2codex.rest;

import java.net.URI;
import java.net.URISyntaxException;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

import com.how2codex.rest.model.Employee;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
public class SpringBootDemoApplicationTests 
{
    @Autowired
    private TestRestTemplate restTemplate;
    
    @LocalServerPort
    int randomServerPort;

    @Test
    public void testAddEmployeeSuccess() throws URISyntaxException 
    {
        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 = this.restTemplate.postForEntity(uri, request, String.class);
        
        //Verify request succeed
        Assert.assertEquals(201, result.getStatusCodeValue());
    }
    
    @Test
    public void testAddEmployeeMissingHeader() throws URISyntaxException 
    {
        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);
        
        ResponseEntity<String> result = this.restTemplate.postForEntity(uri, request, String.class);
        
        //Verify bad request and missing header
        Assert.assertEquals(400, result.getStatusCodeValue());
        Assert.assertEquals(true, result.getBody().contains("Missing request header"));
    }

}

4.Spring BootTestRestTemplate POST示例–演示

将测试类作为JUnit测试执行。它将按正常方式启动服务器并部署API。然后它将执行测试。

您可以在“ JUnit”选项卡中验证测试。

Spring Boot TestRestTemplate结果
Spring Boot TestRestTemplate结果

让我知道如果您在此Spring Boottestresttemplate postforentity示例中有疑问

学习愉快!

saigon has written 1440 articles

Leave a Reply