在JUnit with Spring中,如何使用Mockito(1.10.18)在@Service上创建间谍?
我使用的是Spring3.2.11.RELEASe、JUnit4.12和Mockito1.10.18。在我的JUnit测试中,如何创建@AutowiredSpring服务的间谍(而不是模拟间谍)?下面是服务的声明方式在JUnit with Spring中,如何使用Mockito(1.10.18)在@Service上创建间谍?,spring,junit,mockito,spy,Spring,Junit,Mockito,Spy,我使用的是Spring3.2.11.RELEASe、JUnit4.12和Mockito1.10.18。在我的JUnit测试中,如何创建@AutowiredSpring服务的间谍(而不是模拟间谍)?下面是服务的声明方式 @Service("orderService") public class OrderServiceImpl implements OrderService, InitializingBean { 下面是我的JUnit测试是如何设置的 @RunWith(SpringJUnit4
@Service("orderService")
public class OrderServiceImpl implements OrderService, InitializingBean
{
下面是我的JUnit测试是如何设置的
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class ProcessPDWorkerTest extends AbstractWorkerTest
{
…
@Autowired
protected OrderService m_orderSvc;
与
在那里我有
protected static <T> T getTargetObject(Object proxy)
{
if ((AopUtils.isJdkDynamicProxy(proxy)))
{
try
{
return (T) getTargetObject(((Advised) proxy).getTargetSource().getTarget());
}
catch (Exception e)
{
throw new RuntimeException("Failed to unproxy target.", e);
}
}
return (T) proxy;
}
为我工作:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class ProcessPDWorkerTest extends AbstractWorkerTest {
…
@Spy
@Autowired
protected OrderService m_orderSvc;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(workerObj, "m_orderSvc", m_orderSvc);
}
或者,您可以尝试仅更改此行:
final OrderService orderSvcSpy = Mockito.spy((OrderService)getTargetObject(m_orderSvc));
…
这应该行得通。Mockito.spy()是一个重载的静态方法,编译器在编译时选择Mockito.spy(类)。为什么要监视依赖项?Spy只有在类本身内部测试逻辑时才真正有意义。如果您需要真正的OrderService,只需使用Autowired,否则您可以模拟该类(不使用Spring DI),并最终将一个方法存根为callRealMethod。这就是间谍的目的,或者在这个版本的Mockito中是否有另一个等同于间谍的概念?我很抱歉,但我不知道是哪行代码引发了异常。你能指出这一点吗?你确定
getTargetObject()
正在返回OrderService
的实例吗?#getTargetObject应该使用j7类型推断,但因为没有ref,所以返回的类型是Object。这样做:final OrderService targetObject=getTargetObject(m#u orderSvc)可以解决这个问题。问题帖子显示,在代理对象的情况下,有一个#getTargetObject正在检索原始对象,但我不确定测试逻辑中是否需要#getTargetObject调用,因为在大多数情况下,测试并不真正关心它是目标还是代理对象。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class ProcessPDWorkerTest extends AbstractWorkerTest {
…
@Spy
@Autowired
protected OrderService m_orderSvc;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(workerObj, "m_orderSvc", m_orderSvc);
}
final OrderService orderSvcSpy = Mockito.spy((OrderService)getTargetObject(m_orderSvc));
…