使用注入点测试自定义验证器,WeldUnit 未注入休眠 bean 验证工厂

Testing custom validators with injectionpoints, WeldUnit is not injecting the hibernate bean validation factory

我正在尝试制作一个非常简单的测试用例来测试休眠 bean 验证中的自定义验证器。自定义验证器有一个注入点。

Junit4、BeanValidation 6.1.5.Final、WeldUnit 2.0.0.Final

public class AssertCrsForOffshoreTest extends TestBase {

    //CHECKSTYLE:OFF
    @Rule
//    public WeldInitiator weld = WeldInitiator.from( ValidatorFactory.class ).inject( this ).build();
    public WeldInitiator weld = WeldInitiator.from( ValidatorFactory.class ).build();
    //CHECKSTYLE:ON
    
    @Test
    public void testValidCrs() {

        // prepare test
        BroLocation location = createLocation();
        location.setCrs( BroConstants.CRS_WGS84 );
        BeanWithLocation bean = new BeanWithLocation(  location );

        // action
        Set<ConstraintViolation<BeanWithLocation>> violations = weld.select( ValidatorFactory.class ).get().getValidator().validate( bean );

        // verify
        assertThat( violations ).isEmpty();
    }


}

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

正如 Nikos 在上面评论部分所述,我需要将 ValidationExtension.class 添加到 from fluent 方法并将 cdi 库添加到测试范围。

这是完整的(工作解决方案)


public class AssertCrsForOffshoreTest extends TestBase {

    //CHECKSTYLE:OFF
    // intializes the validation extension and 'registers' the test class as producer of the GeometryServiceHelper  mock
    @Rule
    public WeldInitiator weld = WeldInitiator.from( ValidationExtension.class, AssertCrsForOffshoreTest.class  ).build();
    //CHECKSTYLE:ON

    @ApplicationScoped
    @Produces
    GeometryServiceHelper produceGeometryServiceHelper() throws GeometryServiceException {
        // mock provided to the custom annotation.
        GeometryServiceHelper geometryService = mock( GeometryServiceHelper.class );
        when( geometryService.isOffshore( any( BroLocation.class ) ) ).thenReturn( true );
        return  geometryService;
    }

    @Test
    public void testValidCrs() {

        // prepare test
        BroLocation location = createLocation();
        location.setCrs( BroConstants.CRS_WGS84 );
        BeanWithLocation bean = new BeanWithLocation(  location );

        // action
        Set<ConstraintViolation<BeanWithLocation>> violations = weld.select( ValidatorFactory.class ).get().getValidator().validate( bean );

        // verify
        assertThat( violations ).isEmpty();
    }
}

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

        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator-cdi</artifactId>
            <version>6.1.5.Final</version>
            <scope>test</scope>
        </dependency>