是否可以在PowerMock中对私有静态方法使用部分模拟?

Ric*_*rth 26 java unit-testing mockito powermock

PowerMock主页上的示例中,我看到以下示例,用于部分模拟Mockito的私有方法:

@RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
@PrepareForTest(PartialMockClass.class)
public class YourTestCase {
@Test
public void privatePartialMockingWithPowerMock() {        
    PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());

    // use PowerMockito to set up your expectation
    PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");

    // execute your test
    classUnderTest.execute();

    // Use PowerMockito.verify() to verify result
    PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
}
Run Code Online (Sandbox Code Playgroud)

但是,当我们希望模拟的私有方法是静态的时,这种方法似乎不起作用.我希望创建一个以下类的部分模拟,并使用readFile方法进行模拟:

package org.rich.powermockexample;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import static com.google.common.io.Files.readLines;

public class DataProvider {

    public static List<String> getData() {
        List<String> data = null;
        try {
            data = readFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    private static List<String> readFile() throws IOException {
        File file = new File("/some/path/to/file");
        List<String> lines = readLines(file, Charset.forName("utf-8"));
        return lines;
    }

}
Run Code Online (Sandbox Code Playgroud)

请有人让我知道如何实现这一目标?

Ric*_*rth 33

在做了一些研究之后,似乎PowerMockito.spy()和PowerMockito.doReturn()就是这里所需要的:

package com.richashworth.powermockexample;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;


@RunWith(PowerMockRunner.class)
@PrepareForTest({DataProvider.class})
public class ResultsWriterTest {

    private static List<String> mockData = new ArrayList<String>();
    private ResultsWriter resultsWriter;

    @BeforeClass
    public static void setUpOnce() {
        final String firstLine = "Line 1";
        final String secondLine = "Line 2";
        mockData.add(firstLine);
        mockData.add(secondLine);
    }

    @Before
    public void setUp() {
        resultsWriter = new ResultsWriter();
    }

    @Test
    public void testGetDataAsString() throws Exception {
        PowerMockito.spy(DataProvider.class);
        PowerMockito.doReturn(mockData).when(DataProvider.class, "readFile");

        final String expectedData = "Line 1\nLine 2\n";
        final String returnedString = resultsWriter.getDataAsString();

        assertEquals(expectedData, returnedString);
    }

}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息和完整的代码清单,请查看我的博客文章:https://richashworth.com/post/2012-03-16-turbocharge-your-mocking-framework-with-powermock/

  • 1+:美丽的答案,伙伴.奇迹般有效.甚至连PowerMock网站都没有像你那样描述过这个. (4认同)
  • 精彩!正是我需要的.谢谢 !! (2认同)
  • 找到它,我只需要传递参数,如下所示:PowerMockito.doReturn(mockData).when(DataProvider.class,"readFile",param1,param2); (2认同)

Dav*_*ton 5

测试类:

@RunWith(PowerMockRunner.class)
@PrepareForTest(DataProvider.class)
public class DataProviderTest {

    @Test
    public void testGetDataWithMockedRead() throws Exception {
        mockStaticPartial(DataProvider.class, "readFile");

        Method[] methods = MemberMatcher.methods(DataProvider.class, "readFile");
        expectPrivate(DataProvider.class, methods[0]).andReturn(Arrays.asList("ohai", "kthxbye"));
        replay(DataProvider.class);

        List<String> theData = DataProvider.getData();
        assertEquals("ohai", theData.get(0));
        assertEquals("kthxbye", theData.get(1));
    }

}
Run Code Online (Sandbox Code Playgroud)

正在测试的类(基本上是你的):

public class DataProvider {

    public static List<String> getData() {
        try {
            return readFile();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static List<String> readFile() throws IOException {
        File file = new File("/some/path/to/file");
        return readLines(file, Charset.forName("utf-8"));
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 从变更日志中,我看到:“* Removed mockStatic(Class&lt;?&gt; type, Method method, Method... methods), mockStaticPartial, mockPartial, mock(Class&lt;T&gt; type, Method... methods) &amp; mock(Class &lt;T&gt; type, Method... methods) 来自 Mockito 扩展 API。你应该改用 PowerMockito.spy。” 当我们试图模拟一个静态方法时,如果将被测类的实例提供给 spy() 方法,我无法看到如何做到这一点。 (2认同)