【问题标题】:how to test rest controller with custom annotation in spring boot application如何在 Spring Boot 应用程序中使用自定义注释测试休息控制器
【发布时间】: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


【解决方案1】:

您需要使您的自定义验证器可用于您的 mockMvc 实例。您应该可以通过自动装配 Spring 的 LocalValidatorFactoryBean 来做到这一点

@Autowired
private LocalValidatorFactoryBean validator;

...

@Before
public void setUp() {
    mockMvc = MockMvcBuilders.standaloneSetup(myController)
                  .setValidator(validator).build()
}

【讨论】:

  • 我不能 setValidator(validator),因为我是这样实现的:LocationTypeValidator implements ConstraintValidator
  • 哎呀,我的错。你用什么注释你的测试类?
  • @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = { something.class, something.class})
  • 我已经更新了我的答案。如果这不起作用,请查看stackoverflow.com/questions/23161752/…。它与模拟约束验证器有关,但应该阐明如何让您的 mockMvc 实例识别它。
猜你喜欢
  • 1970-01-01
  • 2019-09-05
  • 2015-05-21
  • 2020-04-27
  • 2018-03-25
  • 2017-05-12
  • 2019-03-27
  • 2017-12-03
相关资源
最近更新 更多