假设我有一个名为 Api 的类,它有一个方法:
public class Api{
public HttpResponse<JsonNode> request() {
try {
return Unirest.get("http://localhost:8080").header("accept", "application/json").asJson();
} catch (UnirestException e) {
throw new RuntimeException(e);
}
}
}
我有一个类:
public class Dao(){
private Api api;
public Dao(Api api){
this.api = api;
}
public Integer test(){
Integer result = api.request().getInteger("result");
return result + 100;
}
}
在我的测试中,我想根据 API.request 方法返回的响应来测试我的业务逻辑。
类似于:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.stub;
import org.json.JSONObject;
import com.mashape.unirest.http.HttpResponse;
public class ApiTest {
private API api = mock(API.class);
public void test() {
HttpResponse<JsonNode> response = null;
JSONObject result = new JSONObject();
response.getBody().getObject();
stub(api.request("")).toReturn(response);
Dao dao = new Dao(api);
assertTrue(dao.test() > 100);
}
}
如何使用 Body“{ number: 10 }”实例化 HttpResponse 以便能够通过模拟返回它?
最佳答案
我就是这样做的:
public class Dao() {
private Api api;
public Dao(Api api){
this.api = api;
}
public Integer test(){
// this is probably not good style
// should iterate through pulling out each piece
Integer result = api.request().getBody().getObject().getInteger("result");
return result + 100;
}
}
public class ApiTest {
private API api = mock(API.class);
public void test() {
JsonNode json = new JsonNode("{\"result\":10}");
HttpResponse<JsonNode> mockResponse = mock(HttpResponse.class);
when(mockResponse.getCode()).thenReturn(200);
when(mockResponse.getBody()).thenReturn(json);
when(api.request(anyString())).thenReturn(mockResponse);
Dao dao = new Dao(api);
// this should be done more carefully as well, check code/body/etc..
assertTrue(dao.test() > 100);
}
}
关于java - 如何为我的模拟实例化 unirest HttpResponse<JsonNode> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38327274/