我正在尝试为一些通常由Spring托管的代码编写JUnit测试。
假设我有这个:
@Configurable
public class A {
@Autowired MyService service;
public void callA() { service.doServiceThings(); }
}我可以使用Mockito和PowerMock为这个类编写一个测试,如下所示:
@RunWith(PowerMockRunner.class)
public class ATest {
@Spy MyService service = new MyService();
@Before void initMocks() { MockitoAnnotations.initMocks(this); }
@Test void test() {
@InjectMocks A a = new A(); // injects service into A
a.callA();
//assert things
}
}但现在我遇到了一个其他类构造A的实例的情况:
public class B {
public void doSomething() {
A a = new A(); // service is injected by Spring
a.callA();
}
}如何将服务注入到在B方法中创建的A的实例中?
@RunWith(PowerMockRunner.class)
public class BTest {
@Spy MyService service = new MyService();
@Before void initMocks() { MockitoAnnotations.initMocks(this); }
@Test testDoSomething() {
B b = new B();
// is there a way to cause service to be injected when the method calls new A()?
b.doSomething();
// assert things
}
}发布于 2014-11-15 20:06:48
字段注入是不好的,但你仍然可以做一件事来轻松地存根A实例化(或者我可能误解了什么)。让B通过构造函数注入一个AFactory。
public class B {
private final AFactory aFactory;
public B(AFactory aFactory) {
this.aFactory=aFactory;
}
public void doSomething() {
A a = aFactory.getA();
a.callA();
}
}然后你可以创建一个aFactory的模型,并通过构造函数将它注入到B中。
https://stackoverflow.com/questions/24718526
复制相似问题