junit - 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);
}
解决方案
Edited because I had gotten the question wrong at first.
简短的回答是:您可能只使用generateHttpPostRequest()
.
更长的答案...
原答案:
如果不知道您的代码,答案是不可能的。模拟用于单元测试。在单元测试中,您拥有被测系统(SUT) 和外部依赖项。对于单元测试,您希望摆脱依赖项中的所有行为,而是完全控制 SUT 在测试期间将看到的内容。单元测试也必须易于阅读,因此复杂的配置是不行的。
一些提示您的决定:
- 永远不要嘲笑 SUT!
- 如果依赖项没有行为并且您可以轻松确定它将呈现您的 SUT 的状态,您可能不需要模拟它。
- 有时可能需要配置一个模拟来返回一个模拟,但如果可能的话,通常应该避免。
推荐阅读
- python - 使用 numba 重载时 Python 内核死机
- python - DJANGO - 如何让我的用户连接到他们的日历?
- python - 以非危险方式基于布尔值选择行
- angular - 如何使用 jasmine-karna 对 Angular 中的嵌套函数进行单元测试
- python - 从鼠标悬停元素中提取链接
- java - 休眠 3 - 5 迁移。Org.hibernate.Criteria:使用 CriteriaBuilder 将 createCriteria(字符串关联,字符串别名)更改为标准 JPA
- python - 如何用自己的生成器覆盖 Python 的随机数?
- algorithm - 待命调度算法
- c# - 为什么我的存储过程在此 Windows 窗体上没有返回任何内容?
- c# - 如何在 switch 表达式中忽略一种元组类型?