PowerMockito模拟单个静态方法并返回另一个静态方法内的对象

时间:2017-05-18 17:22:46

标签: java unit-testing mocking static-methods powermockito

我已经使用PowerMockito的mockStatic功能编写了测试用例来模拟静态类和方法。但我很想在另一个静态方法中模拟一个静态方法。我确实看到了一些例子,包括this但是没有一个实际上帮助我或者我不理解实际的功能? (我无能为力)

EG。我有一个如下课程,完整的代码是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)时,此方法实际上并未被调用。 如何在readPublicKey(...)侧模拟encrypt(...)方法的结果?

1 个答案:

答案 0 :(得分:3)

我在某人SOFpost中找到了解决方案。

在我的情况下,我使用了与PowerMockito相同的部分模拟,如下所示。

PowerMockito.stub(PowerMockito.method(OpenPgpUtility.class, "readPublicKey", InputStream.class)).toReturn(mockPGPPublicKey);

允许我模仿readPublicKey(),但实际调用encrypt()