Spring MockMvc测试:Swagger中的allowableValues未过滤掉错误的参数。

huangapple go评论63阅读模式
英文:

Spring MockMvc test : Swagger allowableValues not filtering bad argument

问题

我有一个需要使用PersonDTO作为请求输入的Java API(Post)。

PersonDTO中有一个名为gender的字段,我使用注解allowableValues = man, woman进行了标注,并且在我从外部调用API时它能够正常工作。如果我传入了其他一些值,它会显示400错误请求代码。

但是当我进行集成测试时,我使用MockMvcgender为其他某个值进行了PersonDTO的post请求,它返回的是200而不是400 - 这意味着allowableValues = man, woman并没有起作用。

我应该如何解决这个问题?

英文:

I have a Java API (Post) that requires a PersonDTO as request input.

There is a field gender in the PersonDTO, I annotated with allowableValues = man, woman and it's working well when I call API externally. If I put some other value, it will show 400 bad request code.

But when I'm doing my integration test, I use MockMvc to do a post PersonDTO with gender of some other value, and it returns 200 instead of 400 - that means allowableValues = man, woman is not working.

How could I fix this ?

答案1

得分: 1

swagger-annotation 仅用于 swagger-ui,以提供一个带有可能值的下拉菜单(请参见 swagger-ui 的示例),因此在 MockMvc 中被忽略。要检查 DTO 中允许的值,请为字段 "gender" 使用枚举而不是字符串,或者使用 Bean-Validation 的 @Pattern 并使用正则表达式来限制 "gender" 字段。

英文:

The swagger-annotation is used for swagger-ui only to provide a dropdown with possible values (see example of swagger-ui) so that is ignored by MockMvc. To check allowed values in your DTO use a Enum for field gender instead of String or use Bean-Validation @Pattern with regex for the field gender.

huangapple
  • 本文由 发表于 2020年7月23日 18:10:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63051822.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定