如何模拟注射链中的类?例如, ServiceA 注入 ServiceB ,注入 ServiceC ( ServiceA - &gt; ServiceB - &gt; ServiceC )。< / p>
在Arquillian测试中,我需要测试 ServiceA 并模拟 ServiceC ,这在我的注射链中被调用。
我想要的是( ServiceA - &gt; ServiceB - &gt; Mocked(ServiceC))。
我怎么能用Arquillian做到这一点?
@RunWith(Arquillian.class)
public class ServiceATest {
@Inject
private ServiceA serviceA;
public void shouldTestServiceA() {
//Mock ServiceC.execute();
serviceA.execute();
}
}
public class ServiceA {
@Inject
private ServiceB serviceB;
public void execute() {
serviceB.execute();
}
}
public class ServiceB {
@Inject
private ServiceC serviceC;
public void execute() {
serviceC.execute();
}
}
//needs to be mocked
public class ServiceC {
public void execute() {
}
}
答案 0 :(得分:0)
您应该考虑通过构造函数注入遵循显式依赖性原则。
而且,课程应该依赖于抽象而不是结核。
对interface StatusTypes {
Active: Status;
Inactive: Status
// This won't be required.
optional?: Status
}
具有已知依赖关系的 ServiceA
是一个实现问题和代码味道。
ServiceC
现在只需要模拟public class ServiceA {
private ServiceB serviceB;
public ServiceA(@Inject ServiceB serviceB) {
this.serviceB = serviceB;
}
public void execute() {
serviceB.execute();
}
}
public interface ServiceB {
void execute();
}
public interface ServiceC {
void execute();
}
并注入测试。
ServiceB
的实施的依赖关系不再是ServiceB