Javax嵌套多重验证

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

Javax nested multiple validations

问题

我有两个类。一个是类A,另一个是类B。类A有一个字符串字段,该字段具有用于检查Base64编码的自定义验证。类B具有类A实例的列表。我需要为此列表添加一个自定义验证器,该验证器检查字节总大小。当我在B中的A实例列表上添加自定义验证器时,它可以正常工作,但是对于我的类A字符串字段的验证器不会触发。如果我移除自定义验证器@ValidTotalSize,那么@ValidEncoding就能正常工作。

Class A {
   @ValidEncoding
   private string content
}

Class B {
   @ValidTotalSize
   private List<A> contentList
}

我的JUnit测试用例 - 在这里,我尝试测试A内部内容的编码。我故意传递不正确的编码,以便出现验证失败,并且我希望断言它。但是在B中的contentList上添加@ValidTotalSize后,@ValidEncoding甚至不会触发。如何确保两个验证都会触发?

@Test
public void testContentEncoding() {
   // 创建具有不正确编码内容的存根
   final Set<ConstraintViolation<B>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(stub);
   Assert.assertTrue(!violations.isEmpty());
}

如何让两者都正常工作?一个用于验证内部内容,然后一个用于验证列表。

英文:

I have two classes. One is class A, the other class B. Class A has a string field which has a custom validation for checking base 64 encoding. Class B has a list of class A instances. I need to add a custom validator for this list which checks total size in bytes. When I add the custom validator on the list of A instances in B, it works but the validator for my Class A string field won't trigger. If I remove custom validator @ValidTotalSize, then @ValidEncoding works.

Class A {
   @ValidEncoding
   private string content
}

Class B {
   @ValidTotalSize
   private List<A> contentList
}

My JUnit - in this I am trying to test for encoding of content inside A. I purposefully pass incorrect encoding so that I have a failed constraint and I want to assert that. But after adding the @ValidTotalSize on contentList inside B, the @ValidEncoding won't even trigger. How can I ensure both validations are triggered?

@Test
public void testContentEncoding() {
   //create stub with incorrect encoded content
   final Set<ConstraintViolation<B>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(stub);
   Assert.assertTrue(!violations.isEmpty());
}

How can I make both work? One to validate the inner content and then one to validate the list.

答案1

得分: 1

我发现了我所缺少的。我需要在contentList上也添加@Valid注解,以触发对列表中每个元素的验证。

@Valid
@ValidTotalSize
private List<A> contentList

英文:

I figured what I was missing. I needed to add the @Valid annotation too on to the contentList to trigger validation of each element in the list.

@Valid
@ValidTotalSize
private List&lt;A&gt; contentList

huangapple
  • 本文由 发表于 2020年8月6日 20:55:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63284090.html
匿名

发表评论

匿名网友

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

确定