我正在使用基于java配置的spring boot。我有以下类结构
@Service
public class Service implements IService{
@autowire
private IProcessor processor;
public void perform(Parameter param){
processor.process(param);
}
}
@Service
public class Processor implements IProcessor {
@autowire
private ProxyFactory factory;
public void process(Parameter param){
final ExternalSysProxy proxy = factory.get(param.getValue(), param.getId());
proxy.call();
}
}
@Repository
public class ProxyFactory {
public Proxy get(String value, String id){
final ExternalSysProxy proxy = new proxy(value, id);
return proxy;
}
}
此处的代理对象调用外部系统。我想通过模拟代理对象来编写集成测试。你能给我一些指导,告诉我如何在这个结构中注入模拟代理对象。
答案 0 :(得分:0)
您可以在调用ProxyFactory.get(String value,String id)时模拟ProxyFactory并返回代理的模拟
我喜欢在我的单元测试中使用Mockito:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ProcessorTest {
@InjectMocks
private Processor processor;
@Mock
private ProxyFactory proxyFactoryMock;
@Mock
private Proxy proxyMock;
@Test
public void myTest() {
Mockito.when(proxyFactoryMock.get("value", "id")).thenReturn(proxyMock);
processor.process(new Parameter("value", "id"));
Mockito.verify(proxyMock, Mockito.times(1)).call();
}
}