gpt4 book ai didi

java - 如何模拟 Unirest 链接方法?

转载 作者:行者123 更新时间:2023-12-02 10:19:12 25 4
gpt4 key购买 nike

我有一个像这样的类,它使用 Unirest API 进行 HTTP POST 调用 -

public class MyClass{
public MyObject getData(){
HttpResponse response = Unirest.post(someURL).header("Content-Type", "application/x-www-form-urlencoded")
.field("Field1", context.getParameter("value for field 1"))
.field("username", context.getParameter("username"))
.field("password", context.getParameter("password"))
.field("field 3", context.getParameter("field 3 value"))
.field("field 4", context.getParameter("field 4 value"))
.asJson();
}
}

在我的模拟课上 -我的mockito中有一个HttpResponse对象,当调用Unirest HTTP post时会返回该对象。我不想通过 Unirest 访问端点,而是想返回我的自定义 httpResponse。

HttpResonse<JsonNode> httpResponse; // my mocked response
Mockito.when(Unirest.post(someURL).header("Content-Type", "application/x-www-form-urlencoded")
.field("Field1", context.getParameter("value for field 1"))
.field("username", context.getParameter("username"))
.field("password", context.getParameter("password"))
.field("field 3", context.getParameter("field 3 value"))
.field("field 4", context.getParameter("field 4 value"))
.asJson()).thenReturn(httpResponse); // this is my custom response

我已经模拟了所有参数的上下文,但仍然收到错误

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:

HttpResponse cannot be returned by getParameter()

getParameter() should return String

有没有一种方法可以更轻松地模拟第 3 方链接方法或更好的实现示例?谢谢!

最佳答案

如果允许重构代码,最简单的方法是将静态调用提取到 protected 方法:

public class MyClass{
public MyObject getData(){
HttpResponse response = postRequest();
}

protected HttpResponse postRequest(){
return Unirest.post(someURL).header("Content-Type", "application/x-www-form-urlencoded")
.field("Field1", context.getParameter("value for field 1"))
.field("username", context.getParameter("username"))
.field("password", context.getParameter("password"))
.field("field 3", context.getParameter("field 3 value"))
.field("field 4", context.getParameter("field 4 value"))
.asJson();
}
}

然后在您的测试用例中,监视被测类并模拟 protected 方法:

public void test(){
MyClass myClass = Mockito.spy(new MyClass());

HttpResonse<JsonNode> httpResponse; // my mocked response

doReturn(httpResponse).when(myClass).postRequest();

...
}

关于java - 如何模拟 Unirest 链接方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54460130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com