问题描述
我想介绍getKeyStore()方法,但是我不知道如何介绍NoSuchAlgorithmException,KeyStoreException,UnrecoverableKeyException和CertificateException的catch块.我的方法是:
I want to cover getKeyStore() methode, But I don't know how to cover catch block for NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException and CertificateException. My methode is :
public static KeyManagerFactory getKeyStore(String keyStoreFilePath)
throws IOException {
KeyManagerFactory keyManagerFactory = null;
InputStream kmf= null;
try {
keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keystoreStream = new FileInputStream(keyStoreFilePath);
keyStore.load(keystoreStream, "changeit".toCharArray());
kmf.init(keyStore, "changeit".toCharArray());
} catch (NoSuchAlgorithmException e) {
LOGGER.error(ERROR_MESSAGE_NO_SUCH_ALGORITHM + e);
} catch (KeyStoreException e) {
LOGGER.error(ERROR_MESSAGE_KEY_STORE + e);
} catch (UnrecoverableKeyException e) {
LOGGER.error(ERROR_MESSAGE_UNRECOVERABLEKEY + e);
} catch (CertificateException e) {
LOGGER.error(ERROR_MESSAGE_CERTIFICATE + e);
} finally {
try {
if (keystoreStream != null){
keystoreStream.close();
}
} catch (IOException e) {
LOGGER.error(ERROR_MESSAGE_IO + e);
}
}
return kmf;
}
我该怎么做?
How do I do it?
推荐答案
您可以模拟 try
块的任何句子以引发要捕获的异常.
You can mock any sentence of the try
block to throw the exception you want to catch.
模拟KeyManagerFactory.getInstance
调用以抛出NoSuchAlgorithmException
的示例.在这种情况下,您将覆盖第一个catch块,您必须对捕获的其他异常(KeyStoreException,UnrecoverableKeyException和CertificateException)执行相同的操作
Example mocking the KeyManagerFactory.getInstance
call to throw NoSuchAlgorithmException
. In that case, you will cover the first catch block, you have to do the same with other exceptions caught (KeyStoreException, UnrecoverableKeyException and CertificateException)
您可以执行以下操作(由于方法getInstance
是static
,因此必须使用 PowerMockito 代替Mockito
,有关更多信息,请参见此问题信息)
You can do as follows (as method getInstance
is static
, you have to use PowerMockito instead Mockito
, see this question for more info)
@PrepareForTest(KeyManagerFactory.class)
@RunWith(PowerMockRunner.class)
public class FooTest {
@Test
public void testGetKeyStore() throws Exception {
PowerMockito.mockStatic(KeyManagerFactory.class);
when(KeyManagerFactory.getInstance(anyString())).thenThrow(new NoSuchAlgorithmException());
}
}
希望有帮助
这篇关于如何使用NoSuchAlgorithmException和KeyStoreException覆盖JUnit的块捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!