powermock跳过某方法_PowerMock:如何取消模拟方法?

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?

I don't see an equivalent to Mockito.reset(). [ Ref: mockito : how to unmock a method? ]

Example:

@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, 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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值