如何测试@Valid 注释是否有效?

Luí*_*res 5 java junit spring hibernate-validator spring-boot

我有以下单元测试:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {EqualblogApplication.class})
@WebAppConfiguration
@TestPropertySource("classpath:application-test.properties")
public class PostServiceTest {
  // ...

  @Test(expected = ConstraintViolationException.class)
  public void testInvalidTitle() {
       postService.save(new Post());  // no title
  }
}
Run Code Online (Sandbox Code Playgroud)

对于代码savePostService是:

public Post save(@Valid Post post) {
    return postRepository.save(post);
}
Run Code Online (Sandbox Code Playgroud)

Post级标有@NotNull在大多数领域。

问题是:没有抛出验证异常

但是,这只发生在测试中。使用应用程序通常会运行验证并引发异常。

注意:我想自动(保存时)而不是手动验证然后保存(因为它更现实)。

Vla*_*scu 9

此解决方案适用于 Spring 5。它也应该适用于 Spring 4。(我已经在 Spring 5 和 SpringBoot 2.0.0 上对其进行了测试)。

有三件事必须在那里:

  1. 在测试类中,提供一个用于方法验证的 bean(在您的示例中为 PostServiceTest)

像这样:

@TestConfiguration
static class TestContextConfiguration {
   @Bean
   public MethodValidationPostProcessor bean() {
      return new MethodValidationPostProcessor();
   }
}
Run Code Online (Sandbox Code Playgroud)
  1. 在方法上有@Valid 注解的类中,还需要在类级别用@Validated (org.springframework.validation.annotation.Validated) 进行注解!

像这样:

@Validated
class PostService {
   public Post save(@Valid Post post) {
       return postRepository.save(post);
   }
}
Run Code Online (Sandbox Code Playgroud)
  1. 您必须在类路径中有一个 Bean Validation 1.1 提供程序(例如 Hibernate Validator 5.x)。实际的提供者将由 Spring 自动检测并自动调整。

MethodValidationPostProcessor 文档中的更多详细信息

希望有帮助

  • 这似乎不适用于 Junit 5。你能帮忙吗 (3认同)