Java 如何使用Mockito模拟Hashmap.get()?

Java 如何使用Mockito模拟Hashmap.get()?,java,junit,mockito,Java,Junit,Mockito,我有这个密码 private final Map<String, ReEncryption> reEncryptionInstances = new HashMap<>(); public ReEncryption getReEncryptionLibInstance () throws ReEncryptionException { final String schemaName = getSchemaName(); final

我有这个密码

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

}
私有最终映射重新加密状态=
新的HashMap();
公共重新加密getReEncryptionLibInstance()
抛出重新加密异常
{
最后一个字符串schemaName=getSchemaName();
final-ReEncryption-ReEncryption=reencryptionstances.get(schemaName);
if(重新加密!=null){
返回重加密;
}
createReEncryptionLibInstance();
if(reEncryptionInstances.get(schemaName)==null){
抛出新的重新加密异常(错误\u库\u未初始化);
}
返回reencryptionstances.get(schemaName);
}

ReEncryptionInstances是一个Hashmap,我想设置ReEncryptionInstances.get(schemaName)==null来测试我的if块。在我的测试课上如何做到这一点?

我可以在这里看到两种方法:

  • 重新加密状态
    包装到另一个类中
  • 部分模拟测试中的类,因此
    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通常是一种不好的做法。所以我只是指向和部分模拟。

    为什么你不能在测试中清除/删除真实地图?当您可以使用某事物的真实实例时,您不应该进行模拟。在编写unittest时,模拟任何集合类型都是无用的。只需使用JVM提供的任何合适的实现。如何从测试类中清除java类中的映射??