gpt4 book ai didi

java - 是否可以使用 PowerMock 来模拟新文件的创建?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:43 26 4
gpt4 key购买 nike

我想介绍一个逻辑,即创建带有单元测试的文件。是否可以模拟 File 类并避免实际创建文件?

最佳答案

模拟构造函数,就像在这个示例代码中一样。 不要忘记将调用“new File(...)”的类放入@PrepareForTest

package hello.easymock.constructor;

import java.io.File;

import org.easymock.EasyMock;
import org.junit.Assert;
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;

@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {

@Test
public void testMockFile() throws Exception {

// first, create a mock for File
final File fileMock = EasyMock.createMock(File.class);
EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
EasyMock.replay(fileMock);

// then return the mocked object if the constructor is invoked
Class<?>[] parameterTypes = new Class[] { String.class };
PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
PowerMock.replay(File.class);

// try constructing a real File and check if the mock kicked in
final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
Assert.assertEquals("/my/fake/file/path", mockedFilePath);
}

}

关于java - 是否可以使用 PowerMock 来模拟新文件的创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16035365/

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