在独立应用程序中使用Jersey的依赖注入

bl3*_*l3e 3 java dependency-injection jersey jersey-2.0 hk2

我这里有一个界面

interface Idemo{
  public int getDemo(int i);
}
Run Code Online (Sandbox Code Playgroud)

这是一个实现

class DemoImpl implements Idemo{
  @Override
  public int getDemo(int i){
    return i+10;
  }
}
Run Code Online (Sandbox Code Playgroud)

并且有一个类依赖于Idemo

class Sample{
  @Inject
  Idemo demo;

  public int getSample(int i){
    return demo.getDemo(i);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在说我想测试Sample类

public class SampleTest extends JerseyTest {
  @Inject
  Sample s; 

  @Override
  protected Application configure() {
    AbstractBinder binder = new AbstractBinder() {
      @Override
      protected void configure() {
        bind(Demo.class).to(Idemo.class);
        bind(Sample.class).to(Sample.class); //**doesn't work**
      }
    };
    ResourceConfig config = new ResourceConfig(Sample.class);
    config.register(binder);
    return config;
  }
  @Test
  public void test_getSample() {
    assertEquals(15, s.getSample(5)); //null pointer exception
  }
}
Run Code Online (Sandbox Code Playgroud)

这里没有创建Sample实例,并且s保持为null.我想这是因为当执行到达指定绑定的行时,已经创建了这个测试类.但我不确定.使用Spring Autowired而不是jersey CDI同样的作品

如果Sample是一个资源/控制器类,测试框架会创建它的一个实例,而不需要注入它,但是可以使用Jersey DI测试任何其他非Web类吗?

Pau*_*tha 6

它与Spring一起使用的原因是测试类由Spring容器管理@RunWith(SpringJUnit4ClassRunner.class).运行器将所有托管对象注入测试对象.JerseyTest不是以这种方式管理的.

如果你愿意,你可以创建自己的跑步者,但你需要了解HK2(泽西岛的DI框架)的工作原理.看一下文档.一切都围绕着ServiceLocator.在独立版本中,您可能会看到类似这样的内容来引导DI容器

ServiceLocatorFactory factory = ServiceLocatorFactory.getInstance();
ServiceLocator locator = factory.create(null);
ServiceLocatorUtilities.bind(locator, new MyBinder());
Run Code Online (Sandbox Code Playgroud)

然后去获得服务,做

Service service = locator.getService(Service.class);
Run Code Online (Sandbox Code Playgroud)

在测试类的情况下,我们不需要获得对服务对象的任何访问,我们可以简单地注入测试对象,使用ServiceLocator:

locator.inject(test);
Run Code Online (Sandbox Code Playgroud)

上面test是在我们的自定义运行器中传递给我们的测试类实例.以下是自定义运行器的示例实现

import java.lang.annotation.*;
import org.glassfish.hk2.api.*;
import org.glassfish.hk2.utilities.*;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.*;

public class Hk2ClassRunner extends BlockJUnit4ClassRunner {

    private final ServiceLocatorFactory factory = ServiceLocatorFactory.getInstance();
    private Class<? extends Binder>[] binderClasses;

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface Binders {

        public Class<? extends Binder>[] value();
    }

    public Hk2ClassRunner(Class<?> cls) throws InitializationError {
        super(cls);
        Binders bindersAnno = cls.getClass().getAnnotation(Binders.class);
        if (bindersAnno == null) {
            binderClasses = new Class[0];
        }
    }

    @Override
    public Statement methodInvoker(FrameworkMethod method, final Object test) {
        final Statement statement = super.methodInvoker(method, test);
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                ServiceLocator locator = factory.create(null);
                for (Class<? extends Binder> c : binderClasses) {
                    try {
                        ServiceLocatorUtilities.bind(locator, c.newInstance());
                    } catch (InstantiationException | IllegalAccessException ex) {
                        throw new RuntimeException(ex);
                    }
                }
                locator.inject(test);
                statement.evaluate();
                locator.shutdown();
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

在运行器中,methodInvoker每个测试方法都会调用它,因此我们为每个被调用的测试方法创建一组新的对象.

这是一个完整的测试用例

@Binders({ServiceBinder.class})
@RunWith(Hk2ClassRunner.class)
public class InjectTest {

    public static class Service {

        @Inject
        private Demo demo;

        public void doSomething() {
            System.out.println("Inside Service.doSomething()");
            demo.doSomething();
        }   
    }

    public static class Demo {
        public void doSomething() {
            System.out.println("Inside Demo.doSomething()");
        }
    }

    public static class ServiceBinder extends AbstractBinder {
        @Override
        protected void configure() {
            bind(Demo.class).to(Demo.class);
            bind(Service.class).to(Service.class);
        }
    }


    @Inject
    private Service service;

    @Test
    public void testInjections() {
        Assert.assertNotNull(service);
        service.doSomething();
    }
}
Run Code Online (Sandbox Code Playgroud)