用注入点测试自定义验证器,weldunit没有注入HibernateBean验证工厂

8yoxcaq7  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(385)

我尝试在hibernatebean验证中制作一个非常简单的测试用例来测试一个定制的验证器。自定义验证器有一个注入点。
junit4,beanvalidation 6.1.5.最终版,weldunit 2.0.0.最终版

  1. public class AssertCrsForOffshoreTest extends TestBase {
  2. //CHECKSTYLE:OFF
  3. @Rule
  4. // public WeldInitiator weld = WeldInitiator.from( ValidatorFactory.class ).inject( this ).build();
  5. public WeldInitiator weld = WeldInitiator.from( ValidatorFactory.class ).build();
  6. //CHECKSTYLE:ON
  7. @Test
  8. public void testValidCrs() {
  9. // prepare test
  10. BroLocation location = createLocation();
  11. location.setCrs( BroConstants.CRS_WGS84 );
  12. BeanWithLocation bean = new BeanWithLocation( location );
  13. // action
  14. Set<ConstraintViolation<BeanWithLocation>> violations = weld.select( ValidatorFactory.class ).get().getValidator().validate( bean );
  15. // verify
  16. assertThat( violations ).isEmpty();
  17. }
  18. }

但是,由于某些原因,它无法解析注入点: org.jboss.weld.exceptions.UnsatisfiedResolutionException: WELD-001334: Unsatisfied dependencies for type ValidatorFactory with qualifiers . 我想我需要引用一个实现而不是 ValidatorFactory.class .

q5lcpyga

q5lcpyga1#

正如nikos在上面的评论部分所描述的,我需要添加 ValidationExtension.class 将cdi库添加到测试范围。
这是完整的(工作解决方案)

  1. public class AssertCrsForOffshoreTest extends TestBase {
  2. //CHECKSTYLE:OFF
  3. // intializes the validation extension and 'registers' the test class as producer of the GeometryServiceHelper mock
  4. @Rule
  5. public WeldInitiator weld = WeldInitiator.from( ValidationExtension.class, AssertCrsForOffshoreTest.class ).build();
  6. //CHECKSTYLE:ON
  7. @ApplicationScoped
  8. @Produces
  9. GeometryServiceHelper produceGeometryServiceHelper() throws GeometryServiceException {
  10. // mock provided to the custom annotation.
  11. GeometryServiceHelper geometryService = mock( GeometryServiceHelper.class );
  12. when( geometryService.isOffshore( any( BroLocation.class ) ) ).thenReturn( true );
  13. return geometryService;
  14. }
  15. @Test
  16. public void testValidCrs() {
  17. // prepare test
  18. BroLocation location = createLocation();
  19. location.setCrs( BroConstants.CRS_WGS84 );
  20. BeanWithLocation bean = new BeanWithLocation( location );
  21. // action
  22. Set<ConstraintViolation<BeanWithLocation>> violations = weld.select( ValidatorFactory.class ).get().getValidator().validate( bean );
  23. // verify
  24. assertThat( violations ).isEmpty();
  25. }
  26. }

您还需要将beanvalidation的cdi扩展添加到单元测试范围

  1. <dependency>
  2. <groupId>org.hibernate.validator</groupId>
  3. <artifactId>hibernate-validator-cdi</artifactId>
  4. <version>6.1.5.Final</version>
  5. <scope>test</scope>
  6. </dependency>
展开查看全部

相关问题