gpt4 book ai didi

java - powerMockito 模拟文件对象

转载 作者:行者123 更新时间:2023-12-04 08:42:25 27 4
gpt4 key购买 nike

我在使用 PowerMockito 模拟 whenNew(File.class) 时遇到问题。这是我要测试的方法:

public void foo() {
File tmpFile = new File("Folder");
if (!tmpFile.exists()) {
if (!configFolder.mkdir()) {
throw new RuntimeException("Can't create folder");
}
}
File oneFileInFolder = new File(tmpFile, "fileOne.txt");
if (oneFileInFolder.exists()){
//do something
}
}

这是我写的测试代码:

static File mockFile;
@Before
public void setUp() throws Exception {
//....some code
mockFolder = mock(File.class);
when(mockFolder.getPath()).thenReturn("Folder");
when(mockFolder.exists()).thenReturn(true);
whenNew(File.class).withParameterTypes(String.class).withArguments(anyString()).thenReturn(mockFolder);
//...some code
}

但是当我调试我的测试用例时,我仍然看到在我的 pwd 中创建了一个真实的文件夹。我不想在运行测试用例时创建文件夹。任何想法?

最佳答案

由于您没有在问题中指定这一点,因此可能缺少以下内容:

@PrepareForTest(ClassYoureCreatingTheFileInstanceIn.class)

根据Wiki :

Note that you must prepare the class creating the new instance of MyClass for test, not the MyClass itself. E.g. if the class doing new MyClass() is called X then you'd have to do @PrepareForTest(X.class) in order for whenNew to work.

换句话说,X 是您示例中包含 foo() 的类。

关于java - powerMockito 模拟文件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18751191/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com