【发布时间】:2018-01-18 05:36:47
【问题描述】:
我有如下定义的控制器
@GetMapping(value="")
public ResponseEntity<JsonResponse> getLocations(@RequestHeader(value="id") String id, @LocationType @RequestParam(value="locationType" ) String P_STS_AREA_TYP) {
...
return new ResponseEntity<>(response,HttpStatus.OK);
}
@LocationType 是自定义注解,定义
@Target({ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = LocationTypeValidator.class)
public @interface LocationType {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
它工作正常,当应用程序正常运行时检查位置类型。但是当我尝试使用 Juint 对其进行测试时,它停止了工作。
@Test
public void should_return_input_invalid_exception_for_invalid_location_type_for_get_location_endpoint() throws Exception {
mockMvc.perform(get("/something/something/something")
.param("locationType", "something")
.header("id", "12345678"))
.andExpect(status().isBadRequest());
}
它通过验证并且不会像应用程序使用相同的位置类型查询参数正常运行时那样进入错误处理逻辑。
用于测试类的注解
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { something.class, something.class})
mockito 作为模拟框架
有人知道如何在 Junit 中使用自定义注释吗?
@Plog,我的验证器定义
public class LocationTypeValidator implements ConstraintValidator<LocationType, String> {
@Autowired
InputValidator inputValidator;
@Override
public void initialize(LocationType locationType) {
}
@Override
public boolean isValid(String locationType, ConstraintValidatorContext constraintValidatorContext) {
return inputValidator.validateLocationType(locationType);
}
}
我无法设置验证器,因为它没有实现验证器接口
【问题讨论】:
-
您是否遇到任何错误?
-
不,只是没有验证
标签: spring spring-boot junit mockito spring-boot-test