【问题标题】:PowerMock and EasyMock method mocking issuePowerMock 和 EasyMock 方法模拟问题
【发布时间】:2012-03-29 19:05:36
【问题描述】:

我是 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。

【问题讨论】:

  • 我能够解决这个问题。一旦我将 File 和 FileOp 类都放在 PrepareForTest 的类级别,测试就通过了正如您在此处看到的,我在类级别放置了一个 @PrepareForTest(File.class),在方法级别放置了 PrepareForTest(FileOp.class)。为什么会这样?

标签: java unit-testing junit4 easymock powermock


【解决方案1】:

您在测试中使用的文件未被模拟。你有你的 fileMock,但它没有在你的测试中使用。您正在测试的方法在以下行中实例化了它自己的新 File 对象:

File file = new File(fileName);

如果您的 deleteFile 方法将采用 File 对象而不是 String,您可以在那里注入您的 mockObject 并检查所有调用是否正确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多