问题
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(...)
?
回答1:
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()
来源:https://stackoverflow.com/questions/44054243/powermockito-mock-single-static-method-and-return-object-inside-another-static-m