[英]Mocking an Object's method calls by EasyMock after injecting it using PowerMock
[英]PowerMock and EasyMock method mocking issue
我是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()时,我将其追溯到deleteFile(“ samplePath”),并且返回false。 但是,我模拟了file.exists()以返回true。
测试中使用的文件不会被模拟。 您有fileMock,但未在测试中使用它。 您正在测试的方法在以下行中实例化它自己的新鲜File对象:
File file = new File(fileName);
如果您的deleteFile方法将使用File对象而不是String,则可以在其中注入模拟对象,并检查所有调用是否正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.