java如何为我的mock实例化unirest HttpResponse<JsonNode>?
假设我有一个名为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的响应测试我的业务逻辑。请求方法返回
比如:
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);
}
}
我如何用一个主体“{number:10}”实例化HttpResponse,以便能够用mock返回它
# 1 楼答案
我就是这样做的:
# 2 楼答案
请参阅此github资源-https://github.com/thejamesthomas/javabank/blob/master/javabank-client/src/test/java/org/mbtest/javabank/ClientTest.java