PowerMockito mock single static method and return object inside another static method

ⅰ亾dé卋堺 提交于 2019-12-07 08:46:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!