Search code examples
javaunit-testingjunit4powermockito

Using PowerMockito to mock Path.getParent()


I have been getting the following error: org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) getParent were found in the class hierarchy of class java.lang.Object.

I'm not sure why. I have tried creating some simple code to narrow down the error and don't understand why this mock isn't working.

The code to test:

public void forTest(File xmlFile){
    Path p = Paths.get(xmlFile.getAbsolutePath());
    p.getParent();
}

The test Code:

@RunWith(PowerMockRunner.class)
@PrepareForTest({XmlFileFunctions.class,Paths.class})
public class XmlFileFunctionsTest {
    @InjectMocks
    XmlFileFunctions xmlFileFunctionsMock;

    @Mock
    File xmlFileMock;
    @Mock
    Path pMock;


    @Test
    public void myTest(){
        when(xmlFileMock.getAbsolutePath()).thenReturn("abc");
        PowerMockito.mockStatic(Paths.class);
        when(Paths.get(Matchers.anyString())).thenReturn(pMock);

        xmlFileFunctionsMock.forTest(xmlFileMock);
        verify(pMock).getParent();
    }

}

Solution

  • After going down a different solution path, I found the following answer: Mockito and PowerMock MethodNotFoundException being thrown

    It seems that changing the version of powermock from 1.6.6 to 1.6.5 fixes this issue.