如何在 JUnit 中使用依赖注入用于 Eclipse E4 插件项目



当我在 JUnit 测试用例中设置上下文以启用测试对象(E4 插件项目)的测试时,该对象对服务 IMyServiceInterface 使用依赖注入,结果始终相同:

InjectionException:无法处理"MyTestObject.myServiceInterface",找不到参数IMyServiceInterface的实际值。

我的想法是在 JUnit 中的测试用例中设置一个 Eclipse 上下文,并将测试对象及其存根依赖项(即不模拟)一起注入。

测试对象是 E4 插件项目中使用的类,具有对注入的服务接口的引用。

我已经尝试了几种在JUnit测试用例中设置上下文的方法(使用ContextInjectionFactory.make(...)和InjectorFactory.getDefault().make(...))来启用测试对象的测试。

这是我的测试对象(E4插件项目)及其两个依赖项的简化;IMyServiceInterface和IMyPartInterface:

@Creatable
@Singleton
public class MyTestObject {
@Inject IMyServiceInterface myServiceInterface;
public void myMethod(IMyPartInterface myPartInterface) {
this.myServiceInterface.update();
myPartInterface.set();
}
}

以下是我的测试用例(JUnit 项目)的简化:

class AllTests {
@Test
void myTestCase() {
InjectorFactory.getDefault().make(MyPart_Stub.class, null);
InjectorFactory.getDefault().make(MyService_Stub.class, null);
MyTestObject myTestObject = InjectorFactory.getDefault().make(MyTestObject.class, null);
}
}

这是我的存根依赖项(JUnit 项目):

public class MyService_Stub implements IMyServiceInterface {
public void update() {
}
}
public class MyPart_Stub implements IMyPartInterface {
public void set() {
}
}

当我运行测试用例时,我得到:InjectionException:无法处理"MyTestObject.myServiceInterface",没有找到参数IMyServiceInterface的实际值"。

终于明白出了什么问题。我不知道 ContextInjectionFactory.make(...) 只创建一个对象(即它也不会在上下文中注入它)。要注入创建的对象,我还必须在上下文中使用 set 方法。这就是我让我的基本示例工作的方式:

class AllTests {
@Test
void myTestCase() {
IEclipseContext context = EclipseContextFactory.create();
IMyPart myPart_Stub = ContextInjectionFactory.make(MyPart_Stub.class, context);
context.set(IMyPart.class, myPart_Stub);
IMyService myService_Stub = ContextInjectionFactory.make(MyService_Stub.class, context);
context.set(IMyService.class, myService_Stub);
MyTestObject myTestObject = ContextInjectionFactory.make(MyTestObject.class, context);
context.set(MyTestObject.class, myTestObject);
}
}

最新更新