Is it possible to use partial mocking for private static methods in PowerMock?

前端 未结 3 1762
星月不相逢
星月不相逢 2020-12-08 07:55

From the examples on the PowerMock homepage, I see the following example for partially mocking a private method with Mockito:

@RunWith(PowerMockRunner.class)         


        
3条回答
  •  不知归路
    2020-12-08 08:03

    Test class:

    @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 theData = DataProvider.getData();
            assertEquals("ohai", theData.get(0));
            assertEquals("kthxbye", theData.get(1));
        }
    
    }
    

    Class being tested (basically yours):

    public class DataProvider {
    
        public static List getData() {
            try {
                return readFile();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    
        private static List readFile() throws IOException {
            File file = new File("/some/path/to/file");
            return readLines(file, Charset.forName("utf-8"));
        }
    
    }
    

提交回复
热议问题