java - 如何使用 Mockito 模拟 Hashmap.get()?
问题描述
我有这个代码
private final Map<String, ReEncryption> reEncryptionInstances =
new HashMap<>();
public ReEncryption getReEncryptionLibInstance ()
throws ReEncryptionException
{
final String schemaName = getSchemaName();
final ReEncryption reEncryption = reEncryptionInstances.get(schemaName);
if (reEncryption != null) {
return reEncryption;
}
createReEncryptionLibInstance();
if(reEncryptionInstances.get(schemaName) == null) {
throw new ReEncryptionException(ERROR_LIBRARY_NOT_INITIALIZED);
}
return reEncryptionInstances.get(schemaName);
}
ReEncryptionInstances 是一个 Hashmap,我想设置 reEncryptionInstances.get(schemaName) == null 来测试我的 if 块。我怎么能在我的测试课上做到这一点?
解决方案
我可以在这里看到两种方法:
- 将其包装
reEncryptionInstances
到不同的类中 - 部分模拟被测类,所以
createReEncryptionLibInstance
不做任何事情。
选项 #1 如下所示:
public class YourClassUnderTest {
private final EncryptionInstances reEncryptionInstances;
public YourClassUnderTest(EncryptionInstances reEncryptionInstances) {
// You can do it in a setter too
// You can inject a Map too
this.reEncryptionInstances = reEncryptionInstances;
}
// ...
}
//...
/**
* You can also mock the EncryptionInstances class.
*/
public class TestEncryptionInstances extends EncryptionInstances {
public ReEncryption getEncryption(String schemaName) {
return null;
}
//...
}
选项 #2 通常是一种不好的做法。所以我只是指向Mockito.spy()和部分嘲笑。
推荐阅读
- c# - 自 Bitbucket 存储库变为私有后下载 GeckoFX 旧版本
- sqlite - 具有多个表的多个打开语句导致 SQLite 中的“SQL 逻辑错误”
- python - 将 dataframe.loc 与多个字符串一起使用
- python-3.x - AttributeError:“审核”对象没有属性“频道”
- python - 当我再次运行程序时,有没有办法可以阻止字典被清空?
- javascript - 在 for 循环中等待 image.onload
- rust - 为什么我在 Bevy 中进行变更检测的尝试从未触发?
- object - 如何获取工作表的对象名称?
- google-cloud-platform - 是否可以在 Google Linux VM 实例中运行 Carla 模拟器
- java - Kotlin - 无法在真实设备中获取位置地址