【问题标题】:How to cover block catch by JUnit with NoSuchAlgorithmException and KeyStoreException如何使用 NoSuchAlgorithmException 和 KeyStoreException 覆盖 JUnit 的块捕获
【发布时间】:2014-10-14 11:36:54
【问题描述】:

我想介绍 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;
}

我该怎么做?

【问题讨论】:

标签: java junit try-catch mockito


【解决方案1】:

您可以mock try 块的任何句子来抛出您想要捕获的异常。

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

您可以执行以下操作(因为方法getInstancestatic,您必须使用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());
   }
}

希望对你有帮助

【讨论】:

  • 您好,通过巡回测试,效果很好。但是当我对 KeyStoreException 做同样的事情时。没用。我的代码是:@Test public void testGetStore() throws Exception { PowerMockito.mockStatic(KeyStore.class); PowerMockito.when(KeyStore.getInstance(Mockito.anyString())).thenThrow(new KeyStoreException()); } 。非常感谢
  • 你在模拟另一个类,KeyStore。也许您忘记更改 @PrepareForTest 注释。应该是:@PrepareForTest(KeyStore.class)
  • 没有。我在@PrepaerForTest 中创建了 KeyStore。我认为问题是 KeyStore.getInstance(Mockito.anyString()) 没有抛出 KeyStoreException。测试通过但没有捕捉到异常
  • 我认为是因为 KeyStore 是单例see
  • @troig,我尝试了上述方法,但它对我不起作用。不幸的是,我无法在评论部分添加完整的代码,这不是答案,所以不想添加我尝试的详细信息作为答案。我意识到这是一个老问题,但它与这个问题完全相同。对我来说,提供方案详细信息的最佳方式是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-23
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 2022-11-23
相关资源
最近更新 更多