测试控制器方法时无法识别请求参数的自定义注释

时间:2018-08-13 02:42:53

标签: spring

请求参数已通过使用以下代码创建的自定义注释@ValidNumber进行了验证。

@Constraint(validatedBy=NumberValidater.class)
@Target(Field, Parameter,..)
@Retention(RUNTIME)
@Documented
public @interface ValidNumber {
    String message() default 
                "{javax.validation.constraints.ValidNumber.message}"
    Class<?>[] groups() default {};
    Class<? extends PayLoad>[] payload() default {};
}

NumberValidator类

public NumberValidator implements <ConstraintValidator, Integer>{
    public void intialize(ValidNumber constraintAnnotation){
    }
    public boolean isValid(Integer number, ConstraintValidatorContext context){
        return(number !=null && number !=0)
    }

配置类:

@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
         return new MethodValidationPostProcessor();
}

控制器类为:

@RestController
@Validated
public StudentController{
    @RequestMapping(value="rollNumber", method=GET)
    public Student getStudentHallticket(@ValidNumber (message= "Invalid RollNumber)
        @RequestParam(vallue = "rollNumber") Integer rollNumber{    
        return service.getHallTicket();
    } 

Java类执行完美并验证了输入值,但是测试类未正确验证输入参数。

测试用例:

class StudentSpec extends Specification{

    @Autowired
    private StudentController studentController;
    @Autowired
    private LocalValidatorFoctoryBean validator
    private MockMvc mockmvc

    def setup(){      
        mockmvc.MockMvcBuilders.standloneSetup(studentController).setValidator(validator).build()
    }       
    def getStudentHallTicket(){

        given:
        def rollNumber = ""

        when:
        def response = mockmvc.perform(get("/rollNumber/").param("rollNumber", rollNumber)

        then:
        response.andExpect(status().isBadRequest())
    }
}



When executed it is giving `isOk()` instead of `isBadRequest()` status that means request parameter not validating when it is null.   
My question is, how do I make sure the custom annotation is available for testing class?

0 个答案:

没有答案