我想知道我应该如何注入(inject)模拟 - 我们有一堆进行服务器调用的类,但是我们的 CI 系统无法访问外部资源,因此不会调用服务器。因此,必须模拟调用并返回硬编码值(例如响应代码)。
所以,这是一段代码:
HttpPost httpRequest = new HttPost(uri);
//some code here
try{
httpRequest.setEntity(entity);
HttpResponse response = httpClient.execute(httpRequest);
...
//other, irrelevant, code is here
那么,是否可以将模拟注入(inject) httpClient.execute(httpRequest) 并从测试单元返回硬编码的响应实体?
谢谢
最佳答案
通常模拟一些对象看起来像这样:
public class TestClass {
private HttpServer server;
public HttpServer getServer() {
return server;
}
public void setServer(HttpServer server) {
this.server = server;
}
public void method(){
//some action with server
}
}
和测试类:
public class TestClassTest {
//class under test
TestClass test = new TestClass();
@org.junit.Test
public void testMethod() throws Exception {
HttpServer mockServer = Mockito.mock(HttpServer.class);
test.setServer(mockServer);
//set up mock, test and verify
}
}
这里有一些有用的链接:
关于java - 使用mockito和powermocks注入(inject)模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17956840/