简体   繁体   English

如何使用 Post 方法测试在 Rest 服务上获取参数

[英]How to test getting parameters on the Rest service using the Post method

I'm trying to test getting parameters for processing a request using the Post method我正在尝试使用 Post 方法测试获取用于处理请求的参数

@RestController
@RequestMapping("api")
public class InnerRestController {

…
    @PostMapping("createList")
    public ItemListId createList(@RequestParam String strListId,
@RequestParam String strDate) {


…
        return null;
    }
}
  • test method测试方法

variant 1变体 1

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class InnerRestControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void innerCreatePublishList() {

        String url = "http://localhost:" + this.port;

        String uri = "/api/createList";

        String listStr = "kl";

        String strDate = "10:21";

        URI uriToEndpoint = UriComponentsBuilder
                .fromHttpUrl(url)
                .path(uri)
                .queryParam("strListId", listStr)
                .queryParam("strDate ", strDate)
                .build()
                .encode()
                .toUri();

        ResponseEntity< ItemListId > listIdResponseEntity =
                restTemplate.postForEntity(uri, uriToEndpoint, ItemListId.class);


    }
}

variant 2变体 2

@Test
void createList() {

        String uri = "/api/createList";

        String listStr = "kl";

        String strDate = "10:21";

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri)
                .queryParam("strListId", listStr)
                .queryParam("strDate ", strDate);

    Map<String, String> map = new HashMap<>();

    map.put("strListId", listStr);//request parameters
    map.put("strDate", strDate);


    ResponseEntity< ItemListId > listIdResponseEntity =
            restTemplate.postForEntity(uri, map, ItemListId.class);


}

Update_1更新_1

In my project exceptions is handled thus:在我的项目中,异常是这样处理的:

  • dto dto
public final class ErrorResponseDto {

    private  String errorMsg;

    private  int status;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss")
    LocalDateTime timestamp;

...
  • handler处理程序
@RestControllerAdvice
public class ExceptionAdviceHandler {

    @ExceptionHandler(value = PublishListException.class)
    public ResponseEntity<ErrorResponseDto> handleGenericPublishListDublicateException(PublishListException e) {

        ErrorResponseDto error = new ErrorResponseDto(e.getMessage());
        error.setTimestamp(LocalDateTime.now());
        error.setStatus((HttpStatus.CONFLICT.value()));

        return new ResponseEntity<>(error, HttpStatus.CONFLICT);
    }   

}

In methods, where necessary, I throw a specific exception...在方法中,如有必要,我会抛出一个特定的异常......

.wsmsDefaultHandlerExceptionResolver: Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'strListId' is not present] .wsmsDefaultHandlerExceptionResolver:已解决 [org.springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数“strListId”不存在]

Who knows what the error is.谁知道错误是什么。 Please explain what you need to add here and why?请说明您需要在此处添加什么以及为什么?

Let's take a look on declarations of postEntity :让我们看一下postEntity声明

postForEntity(URI url, Object request, Class<T> responseType)
...
postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)

As you can see, first argument is either URI or String with uriVariables , but second argument is always request entity.如您所见,第一个参数是URIString with uriVariables ,但第二个参数始终是请求实体。

In you first variant you put uri String as URI and then pass uriToEndpoint as request entity, pretending that it is request object.在您的第一个变体中,您将uri String 作为 URI,然后将uriToEndpoint作为请求实体传递,假装它是请求 object。 Correct solution will be:正确的解决方案是:

ResponseEntity<ItemListId> listIdResponseEntity =
                restTemplate.postForEntity(uriToEndpoint, null, ItemListId.class);

Addressing your comments.处理您的评论。

If server responded with HTTP 409, RestTemplate will throw exception with content of your ErrorResponseDto .如果服务器以 HTTP 409 响应,则RestTemplate将抛出带有ErrorResponseDto内容的异常。 You can catch RestClientResponseException and deserialize server response stored in exception.您可以捕获RestClientResponseException并反序列化存储在异常中的服务器响应。 Something like this:像这样的东西:

try {
  ResponseEntity<ItemListId> listIdResponseEntity =
                restTemplate.postForEntity(uriToEndpoint, null, 
  ItemListId.class);
  
  ...
} catch(RestClientResponseException e) {
  byte[] errorResponseDtoByteArray  = e.getResponseBodyAsByteArray();
  
  // Deserialize byte[] array using Jackson
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 InputStream 传递给 REST 服务 POST 方法 - How to pass InputStream to REST service POST method 使用POST与@FormParam(带有Jersey REST的Java Web服务),遇到405“方法不允许”错误 - Getting 405 “Method Not Allowed” error using POST with @FormParam (Java web service with Jersey REST) 如何模拟服务和测试 POST 控制器方法 - How to mock service and test POST controller method 如何使用邮递员休息客户端发送对象以调用REST服务,以便它将使用适当的方法参数命中以下给定的方法? - how to send object using postman rest client to call REST service so that it will hit the below given method with proper method parameters? 如何使用Hibernate和Jersey在REST服务中发布 - How to POST in REST Service using Hibernate and Jersey 如何在url中为逗号分隔参数传递休息服务的get方法 - How to pass comma separated parameters in a url for the get method of rest service 如何使用REST方法和REST方法获取REST API终结点的访问令牌,当前出现404错误? - How to get the access token of REST API endpoint using Rest Assured with POST method, Currently I am getting 404 error? REST服务获取输入参数的空值 - Rest Service getting null value for input parameters POST方法REST Java中未传递参数 - Parameters not being passed in POST method REST Java 如何使用Mockito测试POST方法 - How to test POST method using Mockito
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM