1

I am writing a test case for my class which uses KeyStore to read certificate and key. I have mocked the KeyStore object and also tried to mock KeyStore.getCertificate() but this mocked method is not getting called. And am getting an error.

Below class represents my class to be tested

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

My Test case goes like this

@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();
}

But I am getting an error as

Caused by: java.security.KeyStoreException: Uninitialized keystore at java.security.KeyStore.getCertificate(KeyStore.java:1079) at com.MyClass.methodToTest(MyClass.java:7)

Please notify me if am doing anything wrong or what is the exact way to achieve my requirement.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Looks like mocking of the `KeyStore.getCertificate` method didn't work. Not an expert in Powermock, but maybe it's got something to do with that the 'getCertificate' method is final? Just a guess. [This](https://stackoverflow.com/questions/12139289/can-powermockito-mock-final-method-in-non-final-concrete-class) might help if this is the case. – jannis Aug 25 '17 at 08:59
  • Hi Jannis, your guess is correct and I tried the way mentioned in your suggested post. But still I am getting same error. I add a tag @PrepareForTest (KeyStore.class) – user3572346 Aug 29 '17 at 09:57

0 Answers0