我是 EasyMock 和 PowerMock 的新手,我可能被一些非常基本的东西困住了。
以下是我想测试的代码
import java.io.File;
public class FileOp() {
private static FileOp instance = null;
public string hostIp = "";
public static FileOp() {
if(null == instance)
instance = new FileOp();
}
private FileOp() {
init();
}
init() {
hostIp = "xxx.xxx.xxx.xxx";
}
public boolean deleteFile(String fileName) {
File file = new File(fileName);
if(file.exists()) {
if(file.delete())
return true;
else
return false;
}
else {
return false;
}
}
}
以下是我的测试代码...
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import java.io.File;
import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(PowerMockRunner.class)
@PrepareForTest(FileOp.class)
public class FileOp_JTest
{
@Test
@PrepareForTest(File.class)
public void deleteFile_Success(){
try {
final String path = "samplePath";
//Prepare
File fileMock = EasyMock.createMock(File.class);
//Setup
PowerMock.expectNew(File.class, path).andReturn(fileMock);
expect(fileMock.exists()).andReturn(true);
expect(fileMock.delete()).andReturn(true);
PowerMock.replayAll(fileMock);
//Act
FileOp fileOp = Whitebox.invokeConstructor(FileOp.class);
assertTrue(fileOp.deleteFile(path));
//Verify
PowerMock.verifyAll();
}
catch (Exception e) {
e.printStackTrace();
assertFalse(true);
}
}
}
由于 assertTrue(fileOp.deleteFile(path)); 测试失败
当调用尝试执行 file.exists() 并且它返回 false 时,我将其追溯到 deleteFile("samplePath") 。但是,我模拟了 file.exists() 以返回 true。