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.