0

我想使用带有 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

我该如何解决这个问题?

4

1 回答 1

2

您的方法createEntityManager()createValidator()返回 bean 都具有.types(Validator.class). 因此,您有两个 bean 符合注入 type 的条件Validator。我认为您将实体管理器输入为验证器是错误的吗?

附带说明一下,在同一个测试课上拥有@ExtendWith(WeldJunit5Extension.class)@EnableWeld是多余的。EnableWeld只是 Junit 原始语法的缩写。

于 2019-07-22T10:56:08.033 回答