java - PowerMock:如何取消模拟一个方法?

标签 java testing powermock

我有一个静态方法,它使用 PowerMock 模拟以抛出异常。 (它会删除文件。)不幸的是,在我的 @After(每次测试后)方法中,我需要在没有模拟的情况下调用此方法。我怎样才能 umock 一个方法?

我没有看到与 Mockito.reset() 等效的东西。 [引用:mockito : how to unmock a method? ]

例子:

@RunWith(PowerMockRunner.class)
@PrepareForTest(PathUtils.class)  // Important: This class has a static method we want to mock.
public class CleaningServiceImplTest2 extends TestBase {

    public static final File testDirPath = new File(CleaningServiceImplTest2.class.getSimpleName());

    @BeforeClass
    public static void beforeAllTests() throws PathException {
        recursiveDeleteDirectory(testDirPath);
    }

    @AfterClass
    public static void afterAllTests() throws PathException {
        recursiveDeleteDirectory(testDirPath);
    }

    private File randomParentDirPath;
    private CleaningServiceImpl classUnderTest;

    @Before
    public void beforeEachTest() {
        randomParentDirPath = new File(testDirPath, UUID.randomUUID().toString()).getAbsoluteFile();
        classUnderTest = new CleaningServiceImpl(randomParentDirPath);
    }

    @After
    public void afterEachTest() throws PathException {
        recursiveDeleteDirectory(randomParentDirPath);
    }

    public static void recursiveDeleteDirectory(File dirPath) throws PathException {
        // calls PathUtils.removeFile(...)
    }

    @Test
    public void run_FailWhenCannotRemoveFile() throws IOException {
        // We only want to mock one method.  Use spy() and not mockStatic().
        PowerMockito.spy(PathUtils.class);

        // These two statements are tightly bound.
        PowerMockito.doThrow(new PathException(PathException.PathExceptionReason.UNKNOWN, randomParentDirPath, null, "message"))
            .when(PathUtils.class);
        PathUtils.removeFile(Mockito.any(File.class));

        classUnderTest.run();
    }
}

最佳答案

这花了我一段时间才弄清楚,所以我正在回答我自己的问题。

据我所知,您需要“撤消”每个模拟。 Mockito.reset()不适用于 Class<?>引用。在测试方法的末尾,添加:

// Undo the mock above because we need to call PathUtils.removeFile() within @After.
PowerMockito.doCallRealMethod().when(PathUtils.class);
PathUtils.removeFile(Mockito.any(File.class));

关于java - PowerMock:如何取消模拟一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19907515/

相关文章:

android - Google Play 应用内结算 - 测试 GetPurchases - 静态响应?

安卓 Kotlin : Mocking a free function using Mockito/PowerMock

java - 使用PowerMock编写单元测试,mocked方法调用失败

java - 无法在我的 JpaRepository 代码中使用 findOne()

java - 避免空检查

c# - 在 TeamCity 中将 dotCover 作为 MSTest 构建步骤的一部分运行

testing - 我如何从 testcafe 框架自定义 testRunner?

java - PowerMock + TestNg | PowerMock + TestNg | PowerMock + TestNg预期异常不起作用

java - 为什么要将 getter 和 setter 方法声明为私有(private)?

java - 为什么我在 Java 中收到有关 "Possible loss of precision"的警告?