如何使用 JerseyTest 依赖限定符模拟注入值

Pet*_*ter 0 java mockito hk2 jersey-test-framework jakarta-ee

我正在尝试模拟包括 jax-rs 层的控制器/资源。该类具有需要注入的依赖项。然而,它也有一些String使用限定符接口注入的值。

基本上,我使用 JerseyTest 运行单个控制器并使用 HK2 进行依赖项注入。我创建了一个ResourceConfig并注册了一个AbstractBinder来绑定注入的类。

这对于常规注入的依赖项来说效果很好,但是当@SomeQualifierInterface添加附加注释时,它会崩溃并出现以下错误:

MultiException stack 1 of 3
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=String,parent=ThingsController,qualifiers={@com.company.SomeQualifierInterface()},position=-1,optional=false,self=false,unqualified=null,10035302)
  ...
MultiException stack 2 of 3
java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.company.ThingsController errors were found
  ...
MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: resolve on com.company.ThingsController
  ...

Run Code Online (Sandbox Code Playgroud)

请参阅下面简化的完整代码示例:

控制器/资源

MultiException stack 1 of 3
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=String,parent=ThingsController,qualifiers={@com.company.SomeQualifierInterface()},position=-1,optional=false,self=false,unqualified=null,10035302)
  ...
MultiException stack 2 of 3
java.lang.IllegalArgumentException: While attempting to resolve the dependencies of com.company.ThingsController errors were found
  ...
MultiException stack 3 of 3
java.lang.IllegalStateException: Unable to perform operation: resolve on com.company.ThingsController
  ...

Run Code Online (Sandbox Code Playgroud)

预选赛界面

import org.slf4j.Logger;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/things")
public class ThingsController {

  @Inject
  private Logger log;

  @Inject
  @SomeQualifierInterface
  private String injectedQualifierValue;

  @GET
  public Response getThings() {
    log.info("getting things");
    System.out.println("Injected value: " + injectedQualifierValue);
    return Response.status(200).entity("hello world!").build();
  }
}
Run Code Online (Sandbox Code Playgroud)

生产服务

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

@Qualifier
@Retention(RUNTIME)
@Target({ TYPE, METHOD, FIELD, PARAMETER })
public @interface SomeQualifierInterface { }
Run Code Online (Sandbox Code Playgroud)

测试

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;

@ApplicationScoped
public class SomeProducerService {

  @Produces
  @Dependent
  @SomeQualifierInterface
  public String getQualifierValue() {
    return "some value!";
  }
}
Run Code Online (Sandbox Code Playgroud)

聚甲醛

import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.slf4j.Logger;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import static junit.framework.TestCase.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;


public class MockedThingsControllerTest extends JerseyTest {

  private Logger logMock = mock(Logger.class);

  @Override
  protected Application configure() {
    ResourceConfig resourceConfig = new ResourceConfig(ThingsController.class);
    resourceConfig.register(new AbstractBinder() {
      @Override
      protected void configure() {
        bind(logMock).to(Logger.class);

        bind("some mocked value").to(String.class); // Doesn't work
        bind(new SomeProducerService()).to(SomeProducerService.class); // Doesn't work
      }
    });
    return resourceConfig;
  }

  @Test
  public void doSomething() {
    Response response = target("/things").request().get();
    assertEquals(200, response.getStatus());
    verify(logMock).info("getting things");
  }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 5

解决了!

首先,使用AbstractBinderfromorg.glassfish.hk2.utilities.binding.AbstractBinder而不是org.glassfish.jersey.internal.inject.AbstractBinder

其次,创建一个扩展AnnotationLiteral并实现该接口的类。

最后,将值绑定到 aTypeLiteral并将 QualifiedBy 设置为 AnnotationLiteral。

完整代码:

import org.glassfish.hk2.api.AnnotationLiteral;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import org.slf4j.Logger;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import static junit.framework.TestCase.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;


public class MockedThingsControllerTest extends JerseyTest {

  private Logger logMock = mock(Logger.class);

  @Override
  protected Application configure() {
    ResourceConfig resourceConfig = new ResourceConfig(ThingsController.class);
    resourceConfig.register(new AbstractBinder() {
      @Override
      protected void configure() {
        bind(logMock).to(Logger.class);
        bind("some mocked value").to(new TypeLiteral<String>() {}).qualifiedBy(new SomeQualifierLiteral());
      }
    });
    return resourceConfig;
  }

  @Test
  public void doSomething() {
    Response response = target("/things").request().get();
    assertEquals(200, response.getStatus());
    verify(logMock).info("getting things");
  }

  static class SomeQualifierLiteral extends AnnotationLiteral<SomeQualifierInterface> implements SomeQualifierInterface {}
}
Run Code Online (Sandbox Code Playgroud)