在我使用 PowerMock 测试的一个类中,我有一个类的以下实例化
EmailMessage msg = new EmailMessage(getExchangeSession());
EmailMessage
是我正在嘲笑的第三方工具,而getExchangeSession()
它是一种继承的受保护方法。我需要嘲笑,EmailMessage
但我真的不在乎调用getExchangeSession()
.
目前我有以下内容,但getExchangeSession()
仍然调用该方法:
@RunWith(PowerMockRunner.class)
@PrepareForTest({EmailProvider.class, ExchangeService.class})
public class MyTest {
@Test
public void test() {
EmailMessage emailMessage = createMock(EmailMessage.class);
ExchangeService exchangeService = createMock(ExchangeService.class);
expectNew(EmailMessage.class, exchangeService).andReturn(emailMessage);
// test setup and call to the class under test
Email email = new Email();
new EmailProvider().send(email);
}
}
public class EmailProvider() extends ClassWithProtectedAccess {
public void send(Email email) {
EmailMessage msg = new EmailMessage(getExchangeSession());
// and here follows the code that I am actually testing
// and which works on the msg (EmailMessage)
// ...
}
}
EmailProvider.send() 的第一行是它运行getExchangeSession()
然后失败。
所以显然我不能跳过对 的调用getExchangeSession()
,我也应该模拟这个方法。这个对吗?如果是这样,使用 PowerMock 和 EasyMock 如何模拟这个受保护的方法?