java - 如何为我的模拟实例化 unirest HttpResponse<JsonNode> ?

标签 java mockito httpresponse unirest

假设我有一个名为 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/

相关文章:

ScalaTest、Mockito、Guice 和 PartialMocking

c# - 从 WCF 服务流式传输文件

http - Response.Redirect 并不总是重定向

java - Tomcat 应用程序管理器的默认用户名密码

java - 如何在代码中处理Android纵向和横向?

java - stub 方法时出现 InvalidUseOfMatchersException

http - 返回响应对象和回显输出有什么区别?

java - 无法打开 JNLP 客户端

java - 有条件地对 map 条目进行分组 - Java 8

android - ArgumentMatchers.any 不能为空