模拟方法调用内部模拟对象

时间:2017-08-24 09:30:54

标签: java unit-testing powermockito

我正在为我的班级编写一个测试用例,它使用KeyStore来读取证书和密钥。我嘲笑了KeyStore对象,并试图模仿KeyStore.getCertificate()但是这个模拟的方法没有被调用。我收到了错误。

下面的类代表我要测试的课程

public class MyClass {
    public void methodToTest() {
        String keystoreFilename = "config/keystore.jks";
        String alias = "alise";
        char[] password = "password".toCharArray();
        KeyStore keystore = getKeyStore(keystoreFilename, password);
        Certificate cert = keystore.getCertificate(alias);
        Key key = keystore.getKey(alias, password);
    }

    public KeyStore getKeyStore(String keystoreFilename, char []password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
        //TODO Cert and Key - remove this once able to get this from TA_DB APIs
        FileInputStream fIn = new FileInputStream(keystoreFilename);
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(fIn, password);
        return keystore;
    }
}

我的测试案例就像这样

@Test
public void testMethod() throws Exception{
    MyClass testClass = PowerMockito.mock(MyClass.class);
    //Mock certificate, key and KeyStore
    KeyStore keyStore = PowerMockito.mock(KeyStore.class);
    Certificate certificate = PowerMockito.mock(Certificate.class);
    Key key = PowerMockito.mock(Key.class);
    PowerMockito.when(keyStore.getCertificate(anyString())).thenReturn(certificate);
    PowerMockito.when(certificate.getEncoded()).thenReturn(TestConstants.RESPONSE_DATA);
    PowerMockito.when(keyStore.getKey(anyString(), anyObject())).thenReturn(key);
    PowerMockito.when(key.getEncoded()).thenReturn(TestConstants.RESPONSE_DATA);
    PowerMockito.when(testClass.getKeyStore(anyString(), any(char[].class))).thenReturn(keyStore);

    testClass.methodToTest();
}

但我收到错误

  

引起:java.security.KeyStoreException:未初始化的密钥库位于   java.security.KeyStore.getCertificate(KeyStore.java:1079)at   com.MyClass.methodToTest(MyClass.java:7)

如果我做错了或者达到我要求的确切方法,请通知我。

0 个答案:

没有答案