我有@RestController
注解的@Validated
,用于验证路径变量/请求参数。:
@RestController
@Validated
public class MainController implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private CarsService carsService;
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public void handleException(ConstraintViolationException ex) {}
@GetMapping(
value = "/",
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getCars(
@RequestParam(value = "offset", defaultValue = "0") @PositiveOrZero
Integer offset,
@RequestParam(value = "limit", defaultValue = paginationLimitDefault)
@Positive @Max(paginationLimitMax)
Integer limit) {
...
...
Map responseBody = new HashMap<String, Object>();
responseBody.put("offset", offset);
responseBody.put("limit", limit);
return ResponseEntity.status(HttpStatus.OK).body(responseBody);
}
}
现在,我想用独立的mockMvc对控制器级别进行单元测试。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class TestMainController {
@InjectMocks
private MainController mainController;
@Mock
private CarsService carsServiceMock;
private MockMvc mockMvc;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(mainController).build();
}
@Test
public void getCarsInvalidOffset() throws Exception {
mockMvc.perform(get("/")
.param("offset", "-1"))
.andExpect(status().isBadRequest());
}
@Test
public void getCarsInvalidLimit() throws Exception {
mockMvc.perform(get("/")
.param("limit", "0"))
.andExpect(status().isBadRequest());
mockMvc.perform(get("/")
.param("limit", "-1"))
.andExpect(status().isBadRequest());
mockMvc.perform(get("/")
.param("limit", "101"))
.andExpect(status().isBadRequest());
}
}
问题是,带有无效参数的测试(上面代码片断中的两个测试)本应返回坏的请求,实际上返回200 OK,结果是测试失败。
我怎样才能解决这个问题呢?谢谢。
StackOverflow:java - Testing @Validated RestController in standalone MockMvc not working - Stack Overflow