PowerMockito模拟单个静态方法并在另一个静态方法中返回对象 [英] PowerMockito mock single static method and return object inside another static method
问题描述
我已经编写了一些测试案例,以使用PowerMockito的mockStatic功能来模拟静态类和方法.但是我正在努力在另一个静态方法中模拟一个静态方法.我确实看到了几个例子,包括 ,但实际上都没有帮助我还是我不了解实际功能? (我一无所知)
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
}
我的测试用例是:
@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));
}
当我调用OpenPgpUtility.encrypt(mockFile, publicKey, flag)
时,实际上未调用此方法.
如何在侧面encrypt(...)
中模拟readPublicKey(...)
方法的结果?
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的部分模拟,如下所示.
In my case, I have used same partial mock of PowerMockito as below.
PowerMockito.stub(PowerMockito.method(OpenPgpUtility.class, "readPublicKey", InputStream.class)).toReturn(mockPGPPublicKey);
这让我可以模拟readPublicKey()
,但实际上是对encrypt()
which letting me to mock readPublicKey()
but an actual call to encrypt()
这篇关于PowerMockito模拟单个静态方法并在另一个静态方法中返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!