【发布时间】:2019-05-11 05:54:39
【问题描述】:
我正在尝试在这里为方法解密编写一个测试用例。
private static Codec codec;
static {
try {
codec = new Codec(encryptionType, encryptionKey, false, true, false);
} catch (CodecException e) {
throw new RuntimeException("Codec initialisation failed", e);
}
}
public static String decrypt(final String toDecrypt) throws CodecException {
String decrypted = codec.decryptFromBase64(toDecrypt);
if (decrypted.endsWith(":")) {
decrypted = decrypted.substring(0, decrypted.length() - 1);
}
return decrypted;
}
测试用例:
@Mock
private Codec codec;
@Test
public void test_decrypt_Success() throws CodecException {
when(codec.decryptFromBase64(TestConstants.toDecrypt)).thenReturn(TestConstants.decrypted);
assertEquals(DocumentUtils.decrypt(TestConstants.toDecrypt), TestConstants.decrypted);
}
由于这是一个静态方法,我无法在测试套件中注入该类的实例并模拟其编解码器。上述代码按预期从编解码器库中的 assert 抛出错误。
您用什么方法来测试这样的静态方法?还是我根本不应该为此编写测试?
【问题讨论】:
-
使用 PowerMock 模拟静态方法。但是你甚至没有在你的 Junit 中调用 decrypt(final String toDecrypt) 方法。没有那个,语句 when(codec.decryptFromBase64(TestConstants.toDecrypt)).thenReturn(TestConstants.decrypted);没有意义。
-
@AnkurChrungoo 我的错。更新了q。我的意思是在断言中调用 decrpyt。
-
@talex,我不是要模拟构造函数或超级构造函数。我想在静态方法中模拟在静态块中初始化的静态变量。
标签: java unit-testing testing static mockito