如何用NoSuchAlgorithmException和KeyStoreException覆盖JUnit的块捕获

我想覆盖getKeyStore()方法,但我不知道如何为NoSuchAlgorithmException,KeyStoreException,UnrecoverableKeyException和CertificateException覆盖catch块。 我的方法是:


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

我该怎么做?

你可以模拟 try块的任何句子来抛出你想要捕获的exception。

KeyManagerFactory.getInstance调用以抛出NoSuchAlgorithmException示例。 在这种情况下,您将覆盖第一个catch块,您必须对捕获的其他exception执行相同的操作(KeyStoreException,UnrecoverableKeyException和CertificateException)

您可以执行以下操作(因为方法getInstancestatic ,您必须使用PowerMockito而不是Mockito ,有关详细信息,请参阅此问题 )

 @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()); } } 

希望能帮助到你