在我正在使用 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一起使用,我如何模拟这种受保护的方法?
如果您要测试的类中包含以下行:
EmailMessage msg = new EmailMessage(getExchangeSession());
然后,您不能通过 powermock 的构造函数来跳过对getExchangeSession()
EmailMessage
的调用 - 它在调用构造函数之前调用,然后将返回值传递给EmailMessage
(无论这是真实的还是模拟的(。
因此,如果您无法设置您的类以使对getExchangeSession
的调用正常工作,则需要按照以下问题中所述模拟该调用:模拟受保护的方法。
由于我正确理解了您的问题,您希望模拟EmailMessage类,但是在创建实例时需要跳过构造函数调用。
... test setup and call to the class under test ...
Email email = new Email();
new EmailProvider().send(email);
问题在于您的测试方式。 您打算在发送方法中测试代码。你不能只调用那个 send(( 方法来测试。您需要编写代码,通过模拟依赖类来测试 send(( 方法中的语句,并测试类中的其他语句
public void testSend() throws Exception
{
// you need to suppress the constructor before you mock the class.
PowerMockito.suppress(PowerMockito.constructor(EmailMessage.class));
EmailMessage emailMessage = PowerMockito.mock(EmailMessage.class);
Email email = new Email();
emailMessage.setSubject(email.getSubject());
// ...your other code here ...
}