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

时间:2016-06-28 16:02:26

标签: java spring junit spring-boot hibernate-validator

我有以下单元测试:

@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
  }
}

save中的PostService代码为:

public Post save(@Valid Post post) {
    return postRepository.save(post);
}

Post类在大多数字段中都标有@NotNull

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

然而,这只发生在测试中。 使用该应用程序通常会运行验证并抛出异常。

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

2 个答案:

答案 0 :(得分:3)

此解决方案适用于Spring 5.它也适用于Spring 4。 (我已经在Spring 5和SpringBoot 2.0.0上测试了它。)

有三件事需要:

  1. 在测试类中,提供用于方法验证的bean(在您的示例中为PostServiceTest)
  2. 像这样:

    @TestConfiguration
    static class TestContextConfiguration {
       @Bean
       public MethodValidationPostProcessor bean() {
          return new MethodValidationPostProcessor();
       }
    }
    
    1. 在方法上有@Valid注释的类中,您还需要在类级别使用@Validated(org.springframework.validation.annotation.Validated)对其进行注释!
    2. 像这样:

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

        中的更多详情

        希望有所帮助

答案 1 :(得分:0)

这是我通过将 select t.teamid, t.teamName, EmployeeIdentity, e.employeeid, e.emplyeename from Employee e join (select TeamId, Employeeid, 'Team Member' as EmployeeIdentity from TeamMember union all select teamid, TeamLeaderId, 'Team Leader' as EmployeeIdentity from team) as tm on tm.employeeid = e.employeeid join teams t on tm.TeamId = t.TeamId 加载到上下文中来做到的:

ValidationAutoConfiguration.class

和 MyComponent 类:

@SpringBootTest
@ContextConfiguration(classes = { MyComponent.class, ValidationAutoConfiguration.class
public class MyComponentValidationTest {
  
  @Autowired
  private MyComponent myComponent;

  @Test
  void myValidationTest() {
    String input = ...;
    // static import from org.assertj.core.api.Assertions
    assertThatThrownBy(() -> myComponent.myValidatedMethod(input))
      .isInstanceOf(ConstraintViolationException.class)
      .hasMessageContaining("my error message");
  }

}