我希望closeSession()
方法在被调用时抛出一个异常,这样我就可以测试我的日志记录是否完成。我将Crypto
对象模拟为mockCrypto
,并将其设置如下:
@Test
public void testdecrpyMcpDataExceptions() throws Exception {
Crypto mockCrypto = Mockito.mock(Crypto.class);
try {
mockCrypto = CryptoManager.getCrypto();
logger.info("Cyrpto Initialized");
} finally {
logger.info("Finally");
try {
logger.info("About to close Crypto!");
Mockito.doThrow(new CryptoException("")).when(mockCrypto).closeSession();
mockCrypto.closeSession();
} catch (CryptoException e) {
logger.warn("CryptoException occurred when closing crypto session at decryptMcpData() in CipherUtil : esi");
}
}
}
然而,当我运行它时,我得到了错误:
Argument passed to when() is not a mock!
我嘲笑的类是错误的还是我只是错过了什么?
不要在
处覆盖mockmockCrypto = CryptoManager.getCrypto();
测试@Test(expected=RuntimeException.class)
public void testdecrpyMcpDataExceptions() throws Exception {
Crypto mockCrypto = mock(Crypto.class);
doThrow(new RuntimeException()).when(mockCrypto).closeSession();
mockCrypto.closeSession();
}
没问题。
这一行将覆盖您的mock:
mockCrypto = CryptoManager.getCrypto();