如何验证@RequestParams是否不为空?
2022-09-03 04:01:38
我有一个计算器服务,从用户那里获取操作类型num1和num2。我需要验证用户是否实际输入了这些值,而不仅仅是将其留空。
@RequestMapping(value = "/calculate")
@ResponseBody
public CalculationResult calculate(@RequestParam(name = "op") String operation, @RequestParam(name = "num1") Double num1, @RequestParam(name = "num2") Double num2) {
System.out.print("Operation:" + operation);
Double calculate = calculatorService.calculate(operation, num1, num2);
return new CalculationResult(calculate);
}
我有一个集成测试,我需要通过,因为它目前失败,错误:
{\“timestamp\”:1488875777084,\“status\”:400,\“error\”:\“Bad Request\”,\“exception\”:\“org.springframework.web.method.annotation.MethodArgumentTypeMismatchException\”,\“message\”:\“未能将类型 'java.lang.String' 的值转换为必需的类型 'java.lang.Double';
以下是我的测试用例:
@Test
public void validates_all_parameters_are_set() throws Exception {
ResponseEntity<String> response = template.getForEntity( "/calculate?op=&num1=&num2=",
String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.BAD_REQUEST));
assertThat(response.getBody(), equalTo("{\"error\":\"At least one parameter is invalid or not supplied\"}"));
}
我不知道如何验证这一点。