Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSubstitute to mock a lazy class

//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

like image 580
Kuroro Avatar asked Nov 14 '11 09:11

Kuroro


People also ask

How to mock lazy in c#?

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.

How do you mock static class in NSubstitute?

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.

What is NSubstitute used for?

NSubstitute is a great library for mocking objects for Test Driven Development (TDD) in . NET.

What is NSubstitute C#?

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.


1 Answers

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);
like image 85
David Tchepak Avatar answered Sep 29 '22 18:09

David Tchepak