如何使用NSubstitute模拟懒惰类

本文关键字:模拟 何使用 NSubstitute | 更新日期: 2023-09-27 18:14:46

//Assert
Lazy<INotificationService> notificationService = Substitute.For<Lazy<INotificationService>>();
Service target = new Service(repository, notificationService);
//Act
target.SendNotify("Message");
//Arrange
notificationService.Received().Value.sendNotification(null, null, null, null);
上面的代码抛出一个异常。

惰性初始化类型没有公共的无参数构造函数

我使用c# 4.0和NSubstitute 1.2.1

如何使用NSubstitute模拟懒惰类

根据@sanosdole的评论,我建议使用真正的Lazy实例来返回您的替代品。比如:

var notificationService = Substitute.For<INotificationService>();
var target = new Service(repository, new Lazy<INotificationService>(() => notificationService));
target.SendNotify("Message");
notificationService.ReceivedWithAnyArgs().sendNotification(null, null, null, null);