Search code examples
javajunitmockitopowermock

How Can I Get PowerMock to Return the Expected Value from a Static Method


Consider the following field and method from a class i need to test.

private final static String pathToUUID = "path/to/my/file.txt";

public String getUuid () throws Exception {
    return new String(Files.readAllBytes(Paths.get(pathToUUID)));;
}

The UUID is stored in a file that is created on the application's first run. A file.txt exists in the location indicated by pathToUUID. I am trying (and struggling) to write a unit test for this method.

@RunWith(PowerMockRunner.class)
@PrepareForTest({Files.class})
public class MyTest {

    private final String expected = "19dcd640-0da7-4b1a-9048-1575ee9c5e39";

    @Test
    public void testGetUuid() throws Exception {
        UUIDGetter getter = new UUIDGetter();
        PowerMockito.mockStatic(Files.class);
         when(Files.readAllBytes(any(Path.class)).thenReturn(expected.getBytes());
        String retrieved = getter.getUuid();
        Assert.assertEquals(expectedUUID, retrieved);
    }
}

Unfortunately when().thenReturn() is not called during testing and the test performs as an integration test, reading the file from the file system and returning its value, rather simply than the mock value i expect. However, if i spoof a call to Files.readAllBytes() in the test method and echo the result to the console, the expected value displays.

So, how can i get my method under test to properly function with the PowerMock when()-thenReturn() pattern?


Solution

  • For anyone facing a similar problem, i solved this by making the following changes to my test class:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({UUIDStasher.class})
    public class TestUUIDStasher {
    
        private final String expectedUUID = "19dcd640-0da7-4b1a-9048-1575ee9c5e39";
        Path spoofPath = Paths.get("C:\\DIRECTORY");
    
        @Before
        public void setup() throws Exception {
            MockitoAnnotations.initMocks(this);
            PowerMockito.mockStatic(Paths.class);
            PowerMockito.mockStatic(Files.class);
            when(Paths.get(any(String.class))).thenReturn(spoofPath);
            when(Files.readAllBytes(any(Path.class))).thenReturn(expectedUUID.getBytes());
        }
    
        @Test
        public void testGetUUID() throws Exception {
            UUIDStasher stasher = new UUIDStasher();
            String retrieved = stasher.getUuid();
            Assert.assertEquals(expectedUUID, retrieved);
        }
    }