2011-11-14 21 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); 

Đoạn mã trên ném một ngoại lệ.Cách sử dụng NSubstitute để chế nhạo một lớp học lười biếng

Loại lười biếng-khởi tạo không có một cộng đồng, xây dựng parameterless

Tôi đang sử dụng C# 4.0 và NSubstitute 1.2.1

+1

Bạn có thực sự muốn thay thế Lazy ? Tôi sẽ giả định rằng Lazy <> hoạt động und sử dụng constructor Value Factory của nó, cung cấp Substitute.For () làm Value Factory ... – sanosdole

+0

+1 nhận xét của @ sanosdole. Đã đăng câu trả lời đó dưới dạng wiki cộng đồng. –

Trả lời

9

Theo nhận xét của @ sanosdole, tôi sẽ đề nghị sử dụng một ví dụ Lazy để trả lại khoản thay thế của bạn. Một cái gì đó như:

var notificationService = Substitute.For<INotificationService>(); 
var target = new Service(repository, new Lazy<INotificationService>(() => notificationService)); 

target.SendNotify("Message"); 

notificationService.ReceivedWithAnyArgs().sendNotification(null, null, null, null); 
Các vấn đề liên quan