【发布时间】:2014-07-13 00:32:43
【问题描述】:
我正在尝试为一些通常由 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
}
}
【问题讨论】:
-
不容易,这是反对字段注入的绝佳论据。您可能需要使用 Spring 测试上下文。
标签: java spring junit mockito powermock