我有一個計算器服務,獲取用戶的操作類型num1和num2。我需要驗證用戶是否實際輸入了這些值,並且不會將其留空。如何驗證@RequestParams不是空的?
@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\":\"Failed to convert value of type 'java.lang.String' to required type '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\"}"));
}
我不知道如何驗證這一點。
要傳遞NUM2作爲值NUM1;這應該是'/ calculate?op =&num1 =&num2 =' –
謝謝,當我修復,我得到一個「java.lang.AssertionError: 預計:<400> 但:是<200>」 – Saakina
簡單的方法是包裹所有prams bean並使用@valid。 [請點擊此處](http://stackoverflow.com/a/26233302/1038268) – Raghu