如何模拟keystore类并为其方法分配模拟行为?

时间:2016-04-01 10:42:41

标签: java unit-testing mockito keystore powermockito

我有以下方法,我需要编写单元测试。但我无法窥探KeyStore类。它引发了以下异常。

org.mockito.exceptions.base.MockitoException: Unable to create mock instance of type 'KeyStore'

我可以嘲笑它。但是当我去为mock方法分配行为时,它会抛出异常。我打电话的方法和我得到的例外情况如下。

when(keyStoreMock.getCertificate(anyString())).thenReturn(certificateMock);

 java.security.KeyStoreException: Uninitialized keystore

doNothing().when(keyStoreMock).load(any(InputStream.class),Mockito.any(char[].class));

 java.lang.NullPointerException

以下是我正在尝试测试的方法。

     public boolean verifySignature(String filePath, String extractContentsPath, String csvParams)
                throws ServiceSDKException {
            boolean result = false;
            String typeOfCertificateStore = "";
            String certificateStoreProvider = "";
            String certificateName = "";
            SignerInformationVerifier verifier = null;
            if (filePath != null && extractContentsPath != null && csvParams != null && !filePath.isEmpty()
                    && !extractContentsPath.isEmpty() && !csvParams.isEmpty()) {
                try {
                    String[] receivedParams = csvParams.split(",");
                    typeOfCertificateStore = receivedParams[0];
                    certificateStoreProvider = receivedParams[1];
                    certificateName = receivedParams[2];
                } catch (ArrayIndexOutOfBoundsException e) {
                    throw new ServiceSDKException("csvParams should have type of certificate store, certificate store provider and certificate name respectively", e);
                }
                try {
                    Path signedDataFilePath = Paths.get(filePath);
                    Path pathToExtractContents = Paths.get(extractContentsPath);

                    KeyStore msCertStore = KeyStore.getInstance(typeOfCertificateStore, certificateStoreProvider);
                    msCertStore.load(null, null);
                    try {
                        verifier = new JcaSimpleSignerInfoVerifierBuilder()
                                .setProvider(certificateStoreProvider)
                                .build(((X509Certificate) msCertStore.getCertificate(certificateName)));
                    } catch (Exception e) {
                        throw new ServiceSDKException("Exception occurred when building certificate",e);
                    }
                    verify(signedDataFilePath, pathToExtractContents, verifier);
                    result = true;
                } catch (KeyStoreException | NoSuchProviderException | IOException | NoSuchAlgorithmException
                        | CertificateException e) {
                    result = false;
                    throw new ServiceSDKException("Exception occurred while preparing to verify signature " , e);
                }
            } else {
                throw new ServiceSDKException("FilePath,extract contents path or csv params cannot be empty or null");
            }
            return result;
        }

如何模拟KeyStore及其方法行为?请指教。

使用MOCKITO的新测试方法:

@PrepareForTest(KeyStore.class)
    @Test
    public void should_verify_signature_when_verifySignature_called_with_fileName_and_certificate_details_in_verifySignature_method() throws Exception {
        PowerMockito.mockStatic(KeyStore.class);

        KeyStore keyStoreMock = PowerMockito.mock(KeyStore.class);
        PowerMockito.when(KeyStore.getInstance(anyString())).thenReturn(keyStoreMock);
        Mockito.doNothing().when(keyStoreMock).load(any(InputStream.class), Mockito.any(char[].class));
        Certificate certificateMock = Mockito.mock(Certificate.class);
        when(keyStoreMock.getCertificate(anyString())).thenReturn(certificateMock);

        PowerMockito.when(KeyStore.getInstance("Windows-MY", "MoonMSCAPI")).thenReturn(keyStoreMock);
        boolean result = signatureUtil.verifySignature("src//test//java//Updates.zip.signed.pkcs7"
                , "src//test//java//Updates-retrieved.zip", "Windows-MY,MoonMSCAPI,Software View Certificate Authority");
        Assert.assertTrue(result);

    }

2 个答案:

答案 0 :(得分:6)

你可以在不使用PowerMock的情况下进行模拟,但是会以稍微复杂的方式进行模拟:

KeyStoreSpi keyStoreSpiMock = mock(KeyStoreSpi.class);
KeyStore keyStoreMock = new KeyStore(keyStoreSpiMock, null, "test"){ };
keyStoreMock.load(null);  // this is important to put the internal state "initialized" to true

从现在开始,您只需模拟keyStoreSpiMock,例如:

when(keyStoreSpiMock.engineGetKey(any(), any())).thenReturn(mock(Key.class);

答案 1 :(得分:1)

KeyStore是一个System类(java.security.KeyStore)。您将需要使用该方法来模拟powermock所指定的系统类!

Code example