根据此链接: powermock
如果我有这个课程
public class PersistenceManager {
public boolean createDirectoryStructure(String directoryPath) {
File directory = new File(directoryPath);
if (directory.exists()) {
throw new IllegalArgumentException("\"" + directoryPath + "\" already exists.");
}
return directory.mkdirs();
}
}
我可以测试以下内容:
@RunWith(PowerMockRunner.class)
@PrepareForTest( PersistenceManager.class )
public class PersistenceManagerTest {
@Test
public void testCreateDirectoryStructure_ok() throws Exception {
final String path = "directoryPath";
File fileMock = createMock(File.class);
PersistenceManager tested = new PersistenceManager();
expectNew(File.class, path).andReturn(fileMock);
expect(fileMock.exists()).andReturn(false);
expect(fileMock.mkdirs()).andReturn(true);
replay(fileMock, File.class);
assertTrue(tested.createDirectoryStructure(path));
verify(fileMock, File.class);
}
}
我有以下问题:
我如何测试这个课程:
public class PersistenceManager {
public boolean createDirectoryStructure(String directoryPath) {
File directory = getFile(directoryPath);
if (directory.exists()) {
throw new IllegalArgumentException("\"" + directoryPath + "\" already exists.");
}
return directory.mkdirs();
}
public File getFile(String directoryPath){
return new File(directoryPath);
}
}
我使用的是powerMock 1.5版
答案 0 :(得分:0)
对于Mockito
/ PowerMockito
,您可以使用whenNew()
功能。一旦你将它展开一点,它可能看起来像这样:
PowerMockito.whenNew(File.class).withArguments(directoryPath).thenReturn((File) fileMock)
。
此外,使用Mockito
时请尝试使用Mockito.mock()
创建Mock对象(在本例中为fileMock
。