I have a calculator service that gets the operation type, num1 and num2 from the user. I need to validate that the user actually inputs these values and doesn't just leave it blank.
@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);
}
I have an Integration test that I need to make pass as it is currently failing with error:
{\"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';
Below is my Test Case:
@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\"}"));
}
I don't know how to validate this.
I answered similar problem long before here which you can follow to write your test as well , as follows:
@Validated
public class CalculationController {
@RequestMapping(value = "/calculate")
@ResponseBody
public CalculationResult calculate(
@Valid @NotBlank @RequestParam(name = "op") String operation,
@Valid @NotNull @RequestParam(name = "num1") Double num1,
@Valid @NotNull @RequestParam(name = "num2") Double num2) {
System.out.print("Operation:" + operation);
Double calculate = calculatorService.calculate(operation, num1, num2);
return new CalculationResult(calculate);
}
}
Corresponding @Test should be modified to test for an array of "may not be null" message, as:
@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\":[\"may not be null\",\"may not be null\"]}"));
}