PowerMock:如何取消模拟方法?

kev*_*rpe 14 java testing powermock

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

我没有看到相当于Mockito.reset().[参考:mockito:如何取消模拟方法?]

例:

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

kev*_*rpe 15

我花了一段时间才弄明白,所以我回答了自己的问题.

AFAIK,你需要"撤消"每个模拟. 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));
Run Code Online (Sandbox Code Playgroud)