我无法确定如何模拟特定的代码段。
这是我的方法:
public void sendNotifications(NotificationType type, Person person)
{
List<Notification> notifications = findNotifications(type);
for(Notification notification : notifications)
{
notification.send(person);
}
}
我希望能够使用 JMock 来测试 findNotifications 是否被调用、and 返回预期值以及 send() 是否被调用。
findNotifications 调用我的 Dao,它被 mock 了。通知是一个抽象类。
我有一个像这样的单元测试,但它显然不起作用。它满足前两个期望,但仅此而已。
@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 还很陌生,所以如果我对自己正在做的事情没有太多线索(我没有),我深表歉意。
最佳答案
test mocked methods inside a mocked method.
你真的不能这么做。真实方法中的调用不会被执行,因为您调用的是模拟方法而不是真实方法。
您的第一次尝试未能满足最后两个期望,因为使它们通过的调用仅在 sendNotifications
的实际实现中进行,而不是在您对其进行的模拟中进行。
第二个更接近可行,但您需要将 mockedNotification
添加到您设置为由 的模拟返回的
。notificationEntries
列表中>getByNotificationType
关于java - 如何使用 JMock 在模拟方法内测试模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5655289/