我尝试在控制器类实现的接口上执行一些参数验证。
界面(使用Swagger生成)
@Validated
@Tag(name = "PersonService", description = "the person API")
public interface PersonServiceApi {
@RequestMapping(
method = RequestMethod.GET,
value = "/person",
produces = { "application/json" }
)
Mono<ResponseEntity<Person>> searchPerson(
@NotNull @Pattern(regexp = "[A-Za-z0-9-]+") @Size(min = 1, max = 30) @Parameter(name = "name", required = true) @Valid @RequestParam(value = "name", required = true) String name,
@Pattern(regexp = "^[A-Za-z0-9]+") @Size(min = 0, max = 9) @Parameter(name = "id") @Valid @RequestParam(value = "id", required = false) String id,
@Min(0) @Parameter(name = "offset") @Valid @RequestParam(value = "offset", required = false, defaultValue = "0") Integer offset,
@Min(1) @Max(30) @Parameter(name = "limit") @Valid @RequestParam(value = "limit", required = false, defaultValue = "30") Integer limit,
@Parameter(hidden = true) final ServerWebExchange exchange
);
}
执行控制器:
@RestController
@Slf4j
public class PesrsonController implements PersonServiceApi {
@Override
public Mono<ResponseEntity<Person>> searchPerson(String name, String id, Integer offset, Integer limit,
ServerWebExchange exchange) {
return this.personService.searchperson(name, id, offset, limit)
.subscribeOn(Schedulers.boundedElastic())
.map(ResponseEntity::ok)
.switchIfEmpty(Mono.just(ResponseEntity.noContent().build()));
}
}
Groovy测试:
@Unroll
def '"test person name with null "'() {
given: 'service return person details'
personService.searchperson(name, id, offset, limit) >> Mono.just(new Person())
when: 'searchpseron by name'
def response =personControllerTest.searchPerson(name, id, offset, limit).block()
then:
ConstraintViolationException
where:
name | id | offset | limit | expectedStatus
"" | "750" | 0 | 30 | HttpStatus.BAD_REQUEST
}
我想要验证@NotNull,在传递空的或null的name时,我预期会发生ConstraintViolationException。
我不确定我是否遵循Groovy测试属性,或者我是否应该遵循ValidatorFactory?请在此处指导我
2条答案
按热度按时间gstyhher1#
接口@Validated应该可以工作-https://github.com/spring-projects/spring-boot/issues/17000。很可能是您的控制器返回BadRequest。请记住,RestControllers抛出的是
MethodArgumentNotValidException
,而不是ConstraintViolationException
。我不确定在您的案例中到底发生了什么,因为缺少response/stacktrace,但我的建议是调试它。
最简单的方法是添加一个
Advicer
,然后查看即将出现的异常:j8yoct9x2#
https://www.baeldung.com/javax-validation-method-constraints#3-programmatic-validation