我有一个函数可以将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
是最终类。
所以我嘲笑ExchangeService
和PullSubscription
如下:
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 })