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

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

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

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 .

q5lcpyga

q5lcpyga1#

正如nikos在上面的评论部分所描述的,我需要添加 ValidationExtension.class 将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>

相关问题