簡體   English   中英

是否可以在 PowerMock 中對私有靜態方法使用部分模擬?

[英]Is it possible to use partial mocking for private static methods in 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");
}

但是,當我們希望模擬的私有方法是靜態的時,這種方法似乎不起作用。 我希望創建以下類的部分模擬,並模擬 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;
    }

}

請有人讓我知道這是如何實現的嗎?

在做了更多的研究之后,似乎 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);
    }

}

有關更多詳細信息和完整代碼清單,請在此處查看我的博客文章: https : //richashworth.com/post/turbocharge-your-mocking-framework-with-powermock/

測試類:

@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));
    }

}

正在測試的類(基本上是你的):

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"));
    }

}

通常,僅對超出您控制范圍的類使用靜態模擬(例如java.io.File )。 由於DataProviderreadFile是你自己的,將DataProvider重構為一個適當的類(即使其方法非靜態),將readFile拉出到一個幫助對象中,然后模擬它。 請參閱此答案https://stackoverflow.com/a/8819339/116509

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM