如何使用post方法测试rest服务的参数获取

dwthyt8l  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(276)

我正在尝试使用post方法测试获取用于处理请求的参数

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

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

…
        return null;
    }
}

试验方法
变型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);

    }
}

变型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);

}

更新\u 1
在我的项目中,例外情况是这样处理的:
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;

...

处理程序

@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);
    }   

}

在方法中,必要时,我抛出一个特定的异常。。。
.w.s.m.s.defaulthandlerexceptionresolver:已解析[org.springframework.web.bind.missingservletrequestparameterexception:所需的字符串参数'strlistid'不存在]
谁知道错误是什么。请解释您需要在这里添加什么以及为什么?

l3zydbqr

l3zydbqr1#

让我们看看 postEntity :

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

如你所见,第一个论点是 URI 或者 String with uriVariables ,但第二个参数始终是请求实体。
在你的第一个变种中 uri 字符串作为uri,然后传递 uriToEndpoint 作为请求实体,假装它是请求对象。正确的解决方案是:

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

回答你的意见。
如果服务器响应http 409, RestTemplate 将抛出异常与您的 ErrorResponseDto . 你可以抓住 RestClientResponseException 并反序列化存储在exception中的服务器响应。像这样:

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

  ...
} catch(RestClientResponseException e) {
  byte[] errorResponseDtoByteArray  = e.getResponseBodyAsByteArray();

  // Deserialize byte[] array using Jackson
}

相关问题