首页 > 解决方案 > Mockito - 函数调用其他函数,我应该同时模拟吗?

问题描述

我有两个方法的代码。方法 A 正在调用方法 B。我应该模拟方法 B 吗?或者我可以让方法 A 调用方法 B,因为它只有业务逻辑,没有数据库连接或 httprequests?

    public Response InsertAsset(UpdateRequest apiRequest, String token) throws IOException, InterruptedException
{   
    /* TODO
     * Change hard-coded URL implementation
     */
    String url = "http://test:8080/update";

    User user = userRepository.findByToken(token);

    UpdateRequestRequest = new UpdateRequest();

    generateRequestAPI(Request, user);

    Request.setAsset(apiRequest.getAsset());
    Request.setKey(generateCombinedKey(Request, user));

    // Will throw NullPointerException in case HTTP body cannot be generated
    HttpRequest httpRequest = generateHttpPostRequest(url, Request, token);

    HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());

    return objectMapper.readValue(httpResponse.body(), Response.class);
}

标签: junitmockitopowermockito

解决方案


Edited because I had gotten the question wrong at first.

简短的回答是:您可能只使用generateHttpPostRequest().

更长的答案...

原答案:

如果不知道您的代码,答案是不可能的。模拟用于单元测试。在单元测试中,您拥有被测系统(SUT) 和外部依赖项。对于单元测试,您希望摆脱依赖项中的所有行为,而是完全控制 SUT 在测试期间将看到的内容。单元测试也必须易于阅读,因此复杂的配置是不行的。

一些提示您的决定:

  1. 永远不要嘲笑 SUT!
  2. 如果依赖项没有行为并且您可以轻松确定它将呈现您的 SUT 的状态,您可能不需要模拟它。
  3. 有时可能需要配置一个模拟来返回一个模拟,但如果可能的话,通常应该避免。

推荐阅读