如何模拟密钥库类并将模拟行为分配给其方法? [英] How to mock keystore class and assign mock behavior to its methods?

查看:110
本文介绍了如何模拟密钥库类并将模拟行为分配给其方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法需要编写单元测试.但是我无法监视KeyStore类.它将引发以下异常.

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

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

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

使用MOCKITO的新测试方法:

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

    }

推荐答案

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

KeyStore is a System class (java.security.KeyStore) . You will need to use the approach for mocking system classes as specified with powermock!

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆