我正处于开始编程的阶段,我想问一下如何使用Mockito模拟对象,更具体地说是Unirest响应。 假设我有一个数据库,并且每次测试时我都不会打扰它,我想为此使用Mockito,但是问题是我不确定如何创建将返回的假“ httpResponse”对象。 为了提供一些背景信息,我附上了我的代码:
/**
* This method lists the ID of the activity when requested.
*
* @return the list of all activities
*/
public JSONArray getActivites() {
HttpResponse<JsonNode> jsonResponse = null;
try {
jsonResponse = Unirest
.get("http://111.111.111.111:8080/activity")
.header("accept", "application/json")
.asJson();
} catch (UnirestException e) {
System.out.println("Server is unreachable");
}
JSONArray listOfActivities = jsonResponse.getBody().getArray();
return listOfActivities;
}
所以我想到的是模拟Unirest,然后在调用.get方法时,我将返回伪造的HttpResponse,问题是,我不确定该怎么做,我已经在网上查看并且无法真的很有意义。 是否可以在实际的数据库中进行1次操作,然后“提取”信息并每次都将其用于测试?
答案 0 :(得分:1)
与此同时,原始作者通过 unirest-mocks 提供模拟支持:
马文:
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-mocks</artifactId>
<version>LATEST</version>
<scope>test</scope>
</dependency>
用法:
class MyTest {
@Test
void expectGet(){
MockClient mock = MockClient.register();
mock.expect(HttpMethod.GET, "http://zombo.com")
.thenReturn("You can do anything!");
assertEquals(
"You can do anything!",
Unirest.get("http://zombo.com").asString().getBody()
);
//Optional: Verify all expectations were fulfilled
mock.verifyAll();
}
}
答案 1 :(得分:0)
带有PowerMockRunner,PowerMockito和Mockito的示例代码片段
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Unirest.class})
public class TestApp{
@Before
public void setup() {
PowerMockito.mockStatic(Unirest.class);
}
@Test
public void shouldTestgetActivites() throws UnirestException {
when(Unirest.get(Client.DEFAULT_BASE_URL)).thenReturn(getRequest);
when(getRequest.asJson()).thenReturn(httpResponse);
when(httpResponse.getStatus()).thenReturn(Integer.valueOf(200));
assertThat(something).isEqualTo(true);
}
}
答案 2 :(得分:0)
您可以将调用包装在可基于某些参数提供HttpResponse的包装器类中,而不是直接调用静态成员。这是一个可以在Mockito中轻松模拟的界面。
/**
* This is a wrapper around a Unirest API.
*/
class UnirestWrapper {
private HttpResponse<JsonNode> getResponse(String accept, String url) {
try {
return Unirest
.get(url)
.header("accept", accept)
.asJson();
} catch (UnirestException e) {
System.out.println("Server is unreachable");
}
// Or create a NULL HttpResponse instance.
return null;
}
}
private final UnirestWrapper unirestWrapper;
ThisClassConstructor(UnirestWrapper unirestWrapper) {
this.unirestWrapper = unirestWrapper;
}
/**
* This method lists the ID of the activity when requested.
*
* @return the list of all activities
*/
public JSONArray getActivites() {
HttpResponse<JsonNode> jsonResponse = this.unirestWrapper.getResponse("http://111.111.111.111:8080/activity", "application/json");
if (jsonResponse == null) {
return null;
}
JSONArray listOfActivities = jsonResponse.getBody().getArray();
return listOfActivities;
}
或者您可以使用电源模拟...