您可以通过创建一个FactoryBean
来创建 MyDao
(或任何)要注入您的MyLogic
实例的模拟来做到这一点。
public class FactoryBeanForMocks<T> implements FactoryBean<T> {
private Class<T> mockClass;
public FactoryBeanForMocks(Class<T> mockClass) {
super();
this.mockClass = mockClass;
}
@Override
public T getObject() throws Exception {
return Mockito.mock(mockClass);
}
@Override
public Class<?> getObjectType() {
return mockClass;
}
@Override
public boolean isSingleton() {
return true;
}
}
使工厂 bean 进入您的logicContext.xml
,以便MyDao
可以将模拟注入MyLogic
:
//logicContext.xml
<bean id="myLogic" class="com.MyLogic">
<constructor-arg ref="myDao"/><!--or other type of injection--?
</bean>
<bean id="myDao" class="x.y.z.FactoryBeanForMocks">
<constructor-arg name="mockClass" value="x.y.MyDao"></constructor-arg>
</bean>
这是你的测试课:
@ContextConfiguration("logicContext.xml")
public class BaseLogicTest extends AbstractTestNGSpringContextTests {
@Autowired
private MyLogic myLogic;
//You can inject the mock myDao into it so that you can stub/verify method calls on it
@Autowired
private MyDao myDao;
@Test
public void testMyTestable() {
//...
when(myDao.process()).thenReturn("a");//stubbing myDao.process()
assertEquals("a", myLogic.processRequest());// assuming myLogic.processRequest() calls myDao.process()
}
}