首页 > 解决方案 > 如何在测试 Spring Boot 应用程序的 API 时在 RequestBody 中传递对象

问题描述

我正在尝试测试 Spring Boot 应用程序的 API,而不使用MockMvcor Mockito。我在为 http 帖子设置实体时遇到问题。当实体只是一个字符串时似乎很容易,但当请求涉及一个类时就更难了。

控制器有这个:

@RequestMapping(value = "/dale/search", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<List<DaleSearchReturn>> 
 earchDale(@RequestBody MasterBox tlsSearchObj) {

所以我需要在请求正文中放置一个 MasterBox 对象。这是我在@TEST 代码中尝试过的:

MasterBox masterBox = new MasterBox ("1", "2", "3", "4", "5", "6", "7") ;

HttpEntity<MasterBox> entity = new HttpEntity<>(masterBox);
        
HttpUriRequest request = RequestBuilder.create("POST")
    .setUri("http://localhost:8080/dale_service/dale/search")
    .setEntity(entity).build();

// When
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);

它在 .setEntity 行上给出以下错误...

java.lang.ClassCastException: org.springframework.http.HttpEntity cannot be cast to org.apache.http.HttpEntity
    at TestAPI.givenBox_then200IsReceived(TestAPI.java:48)

我的进口是:

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
//import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import com.ulalaunch.pcplan.models.MasterBox;

标签: javaspring-boot

解决方案


推荐阅读