java - 如何使用 JUnit/Mockito 模拟一个值以在另一种方法中测试条件?
问题描述
我是 JUnit 和 Mockito 的新手,并且正在努力尝试模拟从布尔方法返回的值以命中条件。
我已经尝试过这篇文章的答案,但似乎对此不起作用。我试过用spy,然后CallRealMethod,想不通。
我已经测试了该值何时为真,但我似乎无法进入测试的 else 部分。
这是我所做的一个例子:
ServiceImpl.java 有一个方法 register(),它调用一个布尔方法 shouldRegister()。shouldRegister() 方法只是检查另一个服务以查看布尔值是真还是假,然后返回。
如果为 true,它会构建一个 JsonNode 有效负载来发送,否则,如果为 false,它会从有效负载中删除一个字段。
// ServiceImpl.java:
// in the record() method:
if (body.has("fieldtoBeRemoved")) {
if (shouldRegister()) {
((ObjectNode) body).set("fieldtoBeRemoved");
} else {
// this is the line I am trying to test
((ObjectNode) body).remove("fieldtoBeRemoved");
}
}
// method being called above in the conditional
protected boolean shouldRegister() {
Optional<String> flag = configService.getString("booleanValue");
String stringFlag = flag.orElse("false");
return BooleanUtils.toBoolean(stringFlag);
}
// In the test
@InjectMocks
private ServiceImpl serviceImpl;
@Test
public void testingForFalse() {
serviceImpl = new ServiceImpl();
// what I am struggling with, trying to make the value false,
// so that it hits the else in the record() method in ServiceImpl
// and removes fieldtoBeRemoved from the payload
when(serviceImpl.shouldRegister()).thenCallRealMethod();
doReturn(false).when(spy(serviceImpl)).shouldRegister();
assertThat(fieldtoBeRemoved, is(""));
}
当我运行它时,它失败了,因为 fieldtoBeRemoved 的值不为空,它具有负载中字段的值,它不应该具有。我猜这个值仍然返回为真,因为我没有正确地模拟它/将它设置为这个测试用例的假。我也尝试过模拟对 record() 方法的调用。任何帮助表示赞赏!
解决方案
shouldRegister
如果源和测试在同一个包中并且至少是包私有的,你可以这样做
@Test
public void testingForFalse() {
serviceImpl = new ServiceImpl() {
@Override
public boolean shouldRegister() {
return false;
}
}
// rest of the test
}
在这种情况下,您不需要对此方法进行任何模拟。
推荐阅读
- node.js - 如何添加嵌套节点调度程序
- node.js - 如何在本地保存文件并在数据库中使用 multer on angular 保存路径
- python - 我们可以在 Python 中添加“或”运算符以及 if 和 else 吗?
- docker - 使用 Docker 时共享主机操作系统的内核
- java - 如何使用 ByteBuddy 委托拦截引导类方法
- reactjs - React Material UI:禁用时如何为按钮提供自定义颜色?
- java - 在java中比较来自不同数据库的两个数据集(两个结果集)
- swift - 如何快速更改按钮颜色和背景颜色
- progressive-web-apps - 我们是否需要更新 Play 商店中的 PWA 应用才能发布新的更改?
- python-3.x - 当我在 python 中使用 googletrans 时出现 JSONDecodeError