I have written test cases to mock static classes and methods using PowerMockito's mockStatic feature. But I am strugling to mock one static method inside another static method. I did see few examples including this but none of them actually helping me or I am not understanding the actual functionality? (I'm clueless)
Eg. I have a class as below and complete code is here.
public static byte[] encrypt(File file, byte[] publicKey, boolean verify) throws Exception {
//some logic here
PGPPublicKey encryptionKey = OpenPgpUtility.readPublicKey(new ByteArrayInputStream(publicKey));
//some other logic here
}
public/private static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
//Impl of this method is here
}
My Test case is:
@Test
public void testEncrypt() throws Exception {
File mockFile = Mockito.mock(File.class);
byte[] publicKey = { 'Z', 'G', 'V', 'j', 'b', '2', 'R', 'l', 'Z', 'F', 'B', 'L', 'Z', 'X', 'k', '=' };
boolean flag = false;
PGPPublicKey mockPGPPublicKey = Mockito.mock(PGPPublicKey.class);
InputStream mockInputStream = Mockito.mock(InputStream.class);
PowerMockito.mockStatic(OpenPgpUtility.class);
PowerMockito.when(OpenPgpUtility.readPublicKey(mockInputStream)).thenReturn(mockPGPPublicKey);
System.out.println("Hashcode for PGPPublicKey: " + OpenPgpUtility.readPublicKey(mockInputStream));
System.out.println("Hashcode for Encrypt: " + OpenPgpUtility.encrypt(mockFile, publicKey, flag));
}
When I call OpenPgpUtility.encrypt(mockFile, publicKey, flag)
this method is not actually getting called.
How Can I mock the result of readPublicKey(...)
method in side encrypt(...)
?
PowerMockito is a PowerMock's extension API to support Mockito. It provides capabilities to work with the Java Reflection API in a simple way to overcome the problems of Mockito, such as the lack of ability to mock final, static or private methods.
You can use Moq to mock non-static methods but it cannot be used to mock static methods.
Because there is no instance variable, the class name itself should be used to access the members of a static class. The powerful capabilities of the feature-rich JustMock framework allow you to mock static classes and calls to static members like methods and properties, set expectations and verify results.
I found the solution in SOF in somebody's post.
In my case, I have used same partial mock of PowerMockito as below.
PowerMockito.stub(PowerMockito.method(OpenPgpUtility.class, "readPublicKey", InputStream.class)).toReturn(mockPGPPublicKey);
which letting me to mock readPublicKey()
but an actual call to encrypt()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With