【问题标题】:Mocking Unirest with mockito用 mockito 模拟 Unirest
【发布时间】:2019-08-09 19:36:06
【问题描述】:

我正处于开始编程阶段,我想询问有关使用 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 次,然后“提取”信息并每次都使用该信息进行测试?

【问题讨论】:

  • 模拟 static 需要的方法 PowerMockito

标签: java testing mockito unirest


【解决方案1】:

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);
      }

    }

【讨论】:

  • 所以我一直在查看您的 sn-p,并且在那一行中:when(Unirest.get(Client.DEFAULT_BASE_URL)).thenReturn(getRequest); 我不明白 Unirest.get 被调用时会返回什么“getRequest”。那是“getRequest”对象吗?
  • @BarLerer 是的。它是 GetRequest 的模拟。您可以参考this了解更多详细信息。 github.com/thejamesthomas/javabank/blob/master/javabank-client/…
【解决方案2】:

您可以将调用包装在一个包装类中,该类可以提供基于某些参数的 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;
}

或者你可以使用 power mocks...

【讨论】:

    【解决方案3】:

    同时,原始作者通过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();
        }
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用Mockito.mock(HttpResponse.class) 模拟HttpResponse,并在获取此响应的正文时放入您的json。例如:

      HttpResponse response = Mockito.mock(HttpResponse.class);    
      when(response.getBody()).thenReturn(readFileContent("my_response.json"));
      

      这个 'readFileContent' 只是一种读取我放置响应的文件的方法。你可以把你的json放在那里比较

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-21
        • 2020-11-29
        • 2014-06-16
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        相关资源
        最近更新 更多