PowerMock:如何取消模拟方法? [英] PowerMock: How to unmock a method?

查看:630
本文介绍了PowerMock:如何取消模拟方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态方法,该方法使用PowerMock进行模拟以引发异常。 (它删除文件。)不幸的是,在我的 @After (每次测试后)方法期间,我需要在没有模拟的情况下调用此方法。我该如何模拟方法?

I have a static method that is mocked using PowerMock to throw an exception. (It deletes files.) Unfortunately, during my @After (after-each-test) method, I need to call this method without the mocks. How can I umock a method?

我没有看到等同于 Mockito.reset()的方法。 [Ref: mockito:如何取消模拟方法?]

I don't see an equivalent to Mockito.reset(). [ Ref: 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();
    }
}


推荐答案

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

This took me a while to figure out, so I am answering my own question.

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

AFAIK, you need to "undo" each mock. Mockito.reset() will not work with Class<?> references. At the end of the test method, add:

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

这篇关于PowerMock:如何取消模拟方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆