Search code examples
javajunitmockingmockitopowermockito

Mockito and PowerMockito Error


The following code works with PowerMockito version 1.7.3 and Mockito version 2.9.0

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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

@RunWith(PowerMockRunner.class)
@PrepareForTest({FileUtils.class, Paths.class, Files.class})
public class FileUtilsTest {

    @Test
    public void testGetFileContents_Success() throws Exception {
        String filePath = "c:\\temp\\file.txt";

        Path mockPath = PowerMockito.mock(Path.class);
        PowerMockito.mockStatic(Paths.class);
        PowerMockito.mockStatic(Files.class);

        Mockito.when(Paths.get(Mockito.anyString())).thenReturn(mockPath);
        Mockito.when(Files.readAllBytes(Mockito.isA(Path.class))).thenReturn("hello".getBytes());

        String fileContents = FileUtils.getFileContents(filePath);
        assertNotNull(fileContents);
        assertTrue(fileContents.length() > 0);

        PowerMockito.verifyStatic(Paths.class);
        Paths.get(Mockito.anyString());
        PowerMockito.verifyStatic(Files.class);
        Files.readAllBytes(Mockito.isA(Path.class));
    }

}

However - when I go to the following versions - PowerMockito version 2.0.0-beta.5 and Mockito version 2.12.0 - I get the following error

    org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.nio.file.Paths
Mockito cannot mock/spy because :
 - final class

Any ideas what could be causing this issue or what I need to change?

Thank you Damien


Solution

  • I think you'll have to downgrade / postpone your upgrade to PowerMock v2.x.

    See PowerMockito not compatible Mockito2 since their v2.0.55-beta release.

    All PowerMock v2.x / Mockito v2.x integration work is covered by these two issues:

    It looks like the goal is to have this working in the PowerMock v2.0.0 (and some Mockito 2.x version) but there's no clear statement of when that will be available.