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

Ext*_*me 4 java static-methods unit-testing mocking powermockito

我已经编写了使用PowerMockito的mockStatic功能来模拟静态类和方法的测试用例。但是我正在努力在另一个静态方法中模拟一个静态方法。我确实没有看到包含示例的示例,但是它们都没有真正对我有所帮助,或者我不了解实际功能?(我很无知)

例如。我有一个下面的类,完整的代码在这里

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
}
Run Code Online (Sandbox Code Playgroud)

我的测试用例是:

@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));
    }
Run Code Online (Sandbox Code Playgroud)

当我调用OpenPgpUtility.encrypt(mockFile, publicKey, flag)此方法时,实际上并没有被调用。我该如何readPublicKey(...)在侧面模拟方法的结果 encrypt(...)

Ext*_*me 6

我在某人的帖子中找到了SOF中的解决方案。

就我而言,我使用了下面的PowerMockito的部分模拟。

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

让我嘲笑,readPublicKey()但实际上是encrypt()

  • 你用这个解决方案拯救了我的一天 (2认同)