2011-11-14 63 views
8
//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); 

上面的代碼會引發異常。如何使用NSubstitute來模擬一個懶類

的延遲初始化類型不具有公共,無參數的構造函數

我使用C#4.0和NSubstitute 1.2.1

+1

確實想替代懶惰?我只是假設Lazy <>運行並使用它的Value Factory構造函數,提供Substitute.For ()作爲Value Factory ... – sanosdole

+0

+1給@ sanosdole的評論。已將該答案發布爲社區wiki。 –

回答

9

按@ 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); 
相關問題