gpt4 book ai didi

java - WELD-SE + JUnit5 WELD-001409 : Ambiguous dependencies for type Validator with qualifiers @Default

转载 作者:行者123 更新时间:2023-12-02 09:40:14 25 4
gpt4 key购买 nike

我想使用 WELD SE 和 JEE8 (CDI 2.0) 创建 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 引用,因此首先它可以创建 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

我该如何解决这个问题?

最佳答案

您的方法 - createEntityManager()createValidator() - 返回具有 .types(Validator.class) 的 bean。因此,您有两个符合注入(inject) Validator 类型的 bean。我认为您将实体管理器输入为 validator 是错误的?

顺便说一句,在同一个测试类上使用 @ExtendWith(WeldJunit5Extension.class)@EnableWeld 是多余的。 EnableWeld 只是 Junit 原始语法的缩写。

关于java - WELD-SE + JUnit5 WELD-001409 : Ambiguous dependencies for type Validator with qualifiers @Default,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57143276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com