我有一个测试有问题。
比方说,有一种这样的方法:
public Item doSomething(Some parameters) {
Item item = someMethodDoingSomethingWithParameters(parameters)
return item;
}
但是后来我引入了新功能,发送通知。
public Item doSomething(List<Some> parameters) {
Item item = someMethodDoingSomethingWithParameters(parameters)
sendNotificationToItemOwners(parameters);
return item;
}
此sendNotificationToItemOwners(List<Some> parameters)
方法如下所示:
private void sendNotificationToOwners(parameters) {
parameters.stream().forEach(parameter -> notificationService.sendNotification(paremeter.getOwnerEmail());
}
我不想测试lambda,并且我不想测试NotificationService
,因为它已经被很好地测试了。
我编写的代码是原始代码的非常简化版。这种新的sendNotificationToOwners()
方法的添加使我头疼,测试失败,我正在尝试模拟一些所需的对象,但似乎无法解决我的问题。
我可以完全在测试中省略此方法吗?如果可能的话,那太好了。
我不想测试lambda,
Lambda表达式不能免除单元测试。我会说这是一种非常危险的观察方式。
并且我不想测试
NotificationService
,因为它已经过测试。
然后模拟它,并允许实例通过构造函数或工厂方法注入到测试中的类中(或者,如果您使用的是依赖注入框架,则对字段进行注释)。您的私有lambda仍将执行,但实际上不会使用其他可能复杂的类。如果此处正在测试的类尚未允许在创建时提供NotificationService
的实例,则对其进行重构,以便可以实现inversion of control。
我可以在测试中完全省略此方法吗?如果可能的话,那太好了。
从技术上讲,您可以将私有方法NotificationService
提取到一个单独的类中,然后注入/模拟它,而不是注入sendNotificationToOwners
引用。但是,该类将仅遍历参数并调用NotificationService
。似乎有点矫kill过正。我的偏好是注入NotificationService
,只让lambda运行并在模拟/间谍对象上调用sendNotification
。这也将使您能够测试是否已为每个参数调用了NotificationService
。