//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);
The above code throws an exception.
The lazily-initialized type does not have a public, parameterless constructor
I am using C# 4.0 and NSubstitute 1.2.1
var mockSession = new Mock<ISession>(); var mockWorkfowService = new Mock<IWorkflowService>(); var myClass = new MyClass(); //Make use of the Lazy<T>(Func<T>()) constructor //to return the mock instances myClass. Session = new Lazy<ISession>( () => mockSession. Object); myClass.
NSubstitute can't mock static methods, so if you want to use NSub for this you'll need to rewrite the original class, or wrap the functionality in a new class that you can mock.
NSubstitute is a great library for mocking objects for Test Driven Development (TDD) in . NET.
NSubstitute is a friendly substitute for . NET mocking libraries. It has a simple, succinct syntax to help developers write clearer tests. NSubstitute is designed for Arrange-Act-Assert (AAA) testing and with Test Driven Development (TDD) in mind. NSubstitute.Analyzers.CSharp.
As per @sanosdole's comment, I would suggest using a real Lazy
instance to return your substitute. Something like:
var notificationService = Substitute.For<INotificationService>();
var target = new Service(repository, new Lazy<INotificationService>(() => notificationService));
target.SendNotify("Message");
notificationService.ReceivedWithAnyArgs().sendNotification(null, null, null, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With