我无法确定如何模拟一段特定的代码。
这是我的方法:
public void sendNotifications(NotificationType type, Person person)
{
List<Notification> notifications = findNotifications(type);
for(Notification notification : notifications)
{
notification.send(person);
}
}
我希望能够使用 JMock 来测试是否调用了 findNotifications 并且返回了预期值以及调用了 send() 。
findNotifications 调用我的 Dao 被嘲笑。通知是一个抽象类。
我有一个这样的单元测试,但它显然不起作用。它满足了前两个期望,但仅此而已。
@Test
public void testSendNotifications2()
{
final Person person = new Person();
notificationEntries.add(createEntry1);
Mockery context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }};
final NotificationDao dao = context.mock(NotificationDao.class, "notificationDao");
final Notification mockedNotification = context.mock(V2ADTNotification.class, "mockNotification");
notifications.add(mockedNotification);
final NotifierServiceImpl mockedService = context.mock(NotifierServiceImpl.class, "mockedService");
//NotifierService service = new NotifierServiceImpl(dao);
context.checking(new Expectations() {
{
one(mockedService).setDao(dao);
one(mockedService).sendNotifications(NotificationType.CREATE, person);
one(mockedService).findNotifications(NotificationType.CREATE);
one(dao).getByNotificationType(NotificationType.CREATE);
will(returnValue(notificationEntries));
will(returnValue(notifications));
one(mockedNotification).send(person);
}
});
mockedService.setDao(dao);
mockedService.sendNotifications(NotificationType.CREATE, person);
context.assertIsSatisfied();
}
mockedService.sendNotifications(NotificationType.CREATE, person);
context.assertIsSatisfied();
}
我怎样才能让它按我的意愿工作?
我尝试的另一种方法。它满足前两个期望,但不满足发送一个。
@Test
public void testSendNotifications()
{
final Person person = new Person();
notificationEntries.add(createEntry1);
Mockery context = new JUnit4Mockery() {{ setImposteriser(ClassImposteriser.INSTANCE); }};
final NotificationDao dao = context.mock(NotificationDao.class, "notificationDao");
final Notification mockedNotification = context.mock(V2ADTNotification.class, "mockNotification");
NotifierService service = new NotifierServiceImpl(dao);
context.checking(new Expectations() {
{
one(dao).getByNotificationType(NotificationType.CREATE);
will(returnValue(notificationEntries));
one(mockedNotification).send(person);
}
});
service.sendNotifications(NotificationType.CREATE, person);
context.assertIsSatisfied();
}
我对使用 Jmock 还是很陌生,所以如果看起来我对自己在做什么(我不知道)不太了解,我很抱歉。