Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock keystore class and assign mock behavior to its methods?

I have the below method which I need to write unit tests for. But I cannot spy the class KeyStore. It throws the below exception.

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

I can mock it though. But when I go to assign the behavior for the mock methods it throws exceptions. Methods I called and the exceptions I got are as follows.

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

Below is the method I'm trying to test.

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

How can I mock KeyStore and its method behaviors? Please advice.

NEW TEST METHOD USING 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);

    }
like image 865
AnOldSoul Avatar asked Apr 01 '16 10:04

AnOldSoul


1 Answers

You can mock without usage of the PowerMock it but in a slightly more complicated way:

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

From now you just mock keyStoreSpiMock, for example:

when(keyStoreSpiMock.engineGetKey(any(), any())).thenReturn(mock(Key.class);
like image 99
Andremoniy Avatar answered Oct 03 '22 00:10

Andremoniy