【发布时间】:2014-04-18 13:28:48
【问题描述】:
根据此链接: 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 版
【问题讨论】:
标签: java unit-testing mocking mockito powermock