小编典典

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

java

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

我该怎么做?


阅读 351

收藏
2020-11-30

共1个答案

小编典典

您可以 模拟try块的任何句子以引发要捕获的异常。

示例模拟KeyManagerFactory.getInstance对throw
的调用NoSuchAlgorithmException。在这种情况下,您将覆盖第一个catch块,必须对捕获的其他异常(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());
   }
}

希望能帮助到你

2020-11-30