使用JUnit5的WeldSE-无法注入依赖项

时间:2019-07-18 09:49:45

标签: java-ee-8 weld-se weld-junit5

这是我的服务等级:

@Path("/foo")
@RequestScoped
public class FooService {

    @Inject @Log
    Logger logger;

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String ping() {
        return "pong";
    }
}

在同一模块中,我有一个util类,该类使用带 @Qualifier 批注的Log接口为记录器提供

public class WebResources {

    @Produces
    @RequestScoped
    public FacesContext produceFacesContext() {
        return FacesContext.getCurrentInstance();
    }


    @Produces @Log
    public Logger produceLog(InjectionPoint injectionPoint) {
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }
}

然后我使用JUnit 5 + Weld SE编写了一个UnitTest

@EnableWeld
public class FooTest {

    @WeldSetup
    public WeldInitiator weld = WeldInitiator.from(FooService.class)
            .activate(RequestScoped.class)
            .build();


    @Test
    public void ping(FooService fooService) {

        fooService.ping();

    }

}

这会产生以下错误:

org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type Logger with qualifiers @Log
  at injection point [BackedAnnotatedField] @Inject @Log it.infocert.shop.rest.FooService.logger
  at it.infocert.shop.rest.FooService.logger(FooService.java:0)

如何在单元测试中将@Log依赖项正确添加到Weld SE?

1 个答案:

答案 0 :(得分:1)

问题在于,一旦启动测试容器,Weld不知道类WebResources。它的工作方式是定义容器中包含哪些bean-您可以添加类,包等。

对于您来说,这样更改WeldInitiator的创建就足够了:

@WeldSetup
public WeldInitiator weld = WeldInitiator.from(FooService.class, WebResources.class)
        .activate(RequestScoped.class)
        .build();

请注意,有多种方法可以启动WeldInitiator,从最简单的方法到您使用的org.jboss.weld.environment.se.Weld对象,一路提供您自己的rowCollection对象。

相关问题