Я новичок в EasyMock и PowerMock, и я застрял на чем-то, что очень просто.Мощный метод PowerMock и EasyMock
Ниже мой код, который я хотел бы проверить
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 (путь));
Я проследил его до deleteFile ("samplePath") при вызове пытается выполнить file.exists() и возвращает false. Тем не менее, я высмеял file.exists(), чтобы вернуть true.
Я смог решить проблему. Тест прошел один раз, когда я поместил оба класса File и FileOp на уровне класса для PrepareForTest Я также заметил, что если я удалю @PrepareForTest с уровня класса и поставлю @PrepareForTest ({File.class, FileOp.class}) тесты проходить. Как вы можете видеть здесь, я разместил один уровень @PrepareForTest (File.class) на уровне класса и PrepareForTest (FileOp.class) на уровне метода. Почему это происходит? – maverick