问题描述
我正在尝试做一个非常简单的测试用例,用于测试休眠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>