使用PowerMockito测试Java EWS API中的Pull Subscription

时间:2013-08-09 00:33:43

标签: java mocking exchange-server exchangewebservices ewsjavaapi

我有一个函数可以将PullSubscription获取的事件处理到Microsoft Exchange。

public void processEvents(ExchangeService service, PullSubscription subscription)
            throws Exception {
    GetEventsResults events = subscription.getEvents();
    // Loop through all item-related events.
    for (ItemEvent itemEvent : events.getItemEvents()) {
        if (itemEvent.getEventType() == EventType.NewMail) {
            EmailMessage message = EmailMessage.bind(service, itemEvent.getItemId());
            EmailParser emailParser = new EmailParser();
            emailParser.parse(message, service);
        }
    }
}

我正在尝试使用PowerMockito进行测试,因为ExchangeService是最终类。 所以我嘲笑ExchangeServicePullSubscription如下:

ExchangeService serviceMock = PowerMockito.mock(ExchangeService.class);
PullSubscription subscriptionMock = PowerMockito.mock(PullSubscription.class);

@Test
public void startPullNotification() throws Exception {
    ProcessEmails pr = new ProcessEmails("config.properties");
    pr.startPullNotification(serviceMock);
}

当我尝试使用以下代码对其进行测试时,它会抛出NullPointerException,因为subscription.getEvents()会返回null(即subscriptionMock中没有任何事件)。

我试图通过模拟必须返回的eventResults来阻止它:

when(subscriptionMock.getEvents()).thenReturn(eventResultsMock);

由于在测试函数中未调用getEvents(),因此无效。我想知道如何测试这个功能吗?

http://archive.msdn.microsoft.com/ewsjavaapi

解决方案:

我不得不模拟函数中创建的每个对象。 另外,我必须在类声明上面添加以下内容。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ ClassBeingTested.class })

0 个答案:

没有答案