我正在尝试使用 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);
}
更新_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);
}
}
在方法中,如有必要,我会抛出一个特定的异常......
.wsmsDefaultHandlerExceptionResolver:已解决 [org.springframework.web.bind.MissingServletRequestParameterException:必需的字符串参数“strListId”不存在]
谁知道错误是什么。请说明您需要在此处添加什么以及为什么?