Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何模拟密钥库类并将模拟行为分配给其方法?_Java_Unit Testing_Mockito_Keystore_Powermockito - Fatal编程技术网

Java 如何模拟密钥库类并将模拟行为分配给其方法?

Java 如何模拟密钥库类并将模拟行为分配给其方法?,java,unit-testing,mockito,keystore,powermockito,Java,Unit Testing,Mockito,Keystore,Powermockito,我有下面的方法,我需要为其编写单元测试。但是我不能监视类密钥库。它抛出以下异常 org.mockito.exceptions.base.MockitoException: Unable to create mock instance of type 'KeyStore' 不过我可以嘲笑它。但是当我为mock方法分配行为时,它会抛出异常。我调用的方法和得到的异常如下 when(keyStoreMock.getCertificate(anyString())).thenReturn(certifi

我有下面的方法,我需要为其编写单元测试。但是我不能监视类密钥库。它抛出以下异常

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;
        }
如何模拟密钥库及其方法行为?请给我一些建议

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

    }

您可以在不使用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
从现在起,您只需模拟
keystrespimock
,例如:

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

密钥库
构造函数受保护,但您只需创建一个内部类
私有类keystemock extensed KeyStore
,在重写的构造函数中调用super并使用它即可。