java - 如何使用 NoSuchAlgorithmException 和 KeyStoreException 覆盖 JUnit 的 block 捕获

标签 java junit try-catch mockito

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


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 block 的任何句子来抛出您想要捕获的异常。

模拟 KeyManagerFactory.getInstance 调用以引发 NoSuchAlgorithmException 的示例。在这种情况下,您将覆盖第一个 catch block ,您必须对捕获的其他异常(KeyStoreException、UnrecoverableKeyException 和 CertificateException)执行相同的操作

您可以执行以下操作(由于方法getInstance静态,您必须使用PowerMockito而不是Mockito,请参阅此question以获取更多信息)

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

希望对你有帮助

关于java - 如何使用 NoSuchAlgorithmException 和 KeyStoreException 覆盖 JUnit 的 block 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359882/

相关文章:

php - 新手 : throw new exception - can we change exception name?

java - 某些同等条件不起作用

android - JUnit 5 参数化测试 - 使用 Kotlin 的 @MethodSource 中的 'Cannot invoke non-static method'

java - 可以逃离 JUnit 测试用例吗?

ant - Junit/Ant 重新运行失败的测试

javascript - 在JS中,为什么不记录catch(err)中的参数显示完整的响应对象?

java - jax-ws:设置请求的内容类型

java - 日期选择器 - selenium webdriver java

java - 连续循环应用程序的正确方法是什么

.net - .NET 中的 Try-Catch-Continue