【发布时间】:2016-05-05 20:11:18
【问题描述】:
考虑我需要测试的类中的以下字段和方法。
private final static String pathToUUID = "path/to/my/file.txt";
public String getUuid () throws Exception {
return new String(Files.readAllBytes(Paths.get(pathToUUID)));;
}
UUID 存储在应用程序首次运行时创建的文件中。 file.txt 存在于pathToUUID 指示的位置。我正在尝试(并且正在努力)为此方法编写单元测试。
@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);
}
}
不幸的是,when().thenReturn() 在测试期间没有被调用,并且测试作为集成测试执行,从文件系统读取文件并返回它的值,而不是我期望的模拟值。但是,如果我在测试方法中欺骗了对Files.readAllBytes() 的调用并将结果回显到控制台,则会显示expected 值。
那么,我怎样才能让我的测试方法与 PowerMock when()-thenReturn() 模式一起正常运行?
【问题讨论】:
标签: java junit mockito powermock