0

在我使用 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 如何模拟这个受保护的方法?

4

2 回答 2

1

如果您正在测试的课程中有这一行:

EmailMessage msg = new EmailMessage(getExchangeSession());

那么你不能通过getExchangeSession()powermocking构造函数来跳过调用EmailMessage- 它在构造函数被调用之前被调用,然后返回值被传递给EmailMessage(无论是真实的还是模拟的)。

因此,如果您无法设置您的类以使调用getExchangeSession有效,则需要按照以下问题所述模拟该调用:模拟受保护的方法

于 2013-06-14T11:31:22.283 回答
0

正如我正确理解您的问题一样,您希望模拟 EmailMessage 类,但在创建实例时需要跳过构造函数调用。

    ... test setup and call to the class under test ...
    Email email = new Email();
    new EmailProvider().send(email);

问题在于你的测试方式。您的目的是测试 send 方法中的代码。您不能只调用该 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 ...

}
于 2013-06-13T13:28:32.350 回答