首页 > 解决方案 > 如何使用 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 块。我怎么能在我的测试课上做到这一点?

标签: javajunitmockito

解决方案


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

  1. 将其包装reEncryptionInstances到不同的类中
  2. 部分模拟被测类,所以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()和部分嘲笑。


推荐阅读