![](/img/trans.png)
[英]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.