我想使用带有 JEE8 (CDI 2.0) 的 WELD SE 创建 REST 资源的单元测试。
这是 REST 资源类的代码:
@Path("/members")
@RequestScoped
public class MemberResourceRESTService {
@Inject
private Logger log;
@Inject
private Validator validator;
@Inject
private MemberRepository repository;
@Inject
MemberRegistration registration;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Member> listAllMembers() {
log.info("list all members");
return repository.findAllOrderedByName();
}
我创建了其余的测试junit
@ExtendWith(WeldJunit5Extension.class)
@EnableWeld
public class MemberTest {
@WeldSetup
public WeldInitiator weld = WeldInitiator.from(
MemberResourceRESTService.class,
Resources.class,
WebResources.class,
MemberRepository.class,
MemberRegistration.class)
.addBeans(createValidator(), createEntityManager())
.activate(RequestScoped.class)
.build();
static Bean<?> createValidator() {
return MockBean.builder()
.types(Validator.class)
.scope(ApplicationScoped.class)
.creating(
// Validation.byProvider(HibernateValidator.class).configure().buildValidatorFactory().getValidator()
Validation.buildDefaultValidatorFactory().getValidator()
).build();
}
static Bean<?> createEntityManager() {
return MockBean.builder()
.types(Validator.class)
.scope(ApplicationScoped.class)
.creating(
Persistence.createEntityManagerFactory("primary-test").createEntityManager()
).build();
}
@Test
@DisplayName("list all mambers test")
public void list_all_members(MemberResourceRESTService memberResource) {
final List<Member> members = memberResource.listAllMembers();
Assertions.assertFalse(members.isEmpty());
}
在 pom.xml 中,我在测试范围内添加了 hibernate-validator 引用,因此首先它可以创建验证器。
当我尝试运行测试时,我收到此错误:
org.jboss.weld.exceptions.DeploymentException: WELD-001409: Ambiguous dependencies for type Validator with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject private it.infocert.shop.rest.MemberResourceRESTService.validator
at it.infocert.shop.rest.MemberResourceRESTService.validator(MemberResourceRESTService.java:0)
Possible dependencies:
- org.jboss.weld.junit.MockBean@4893b344,
- org.jboss.weld.junit.MockBean@249e0271
我该如何解决这个问题?