avi
avi

Reputation: 441

How to mock with NSubstitute in IntegrationTest

I have a ContainerFixture class that I use in my integration test which is as per below:

services.AddSingleton(Mock.Of<IWebHostEnvironment>(w =>
 w.EnvironmentName == "Development" &&
 w.ApplicationName == "Application.WebUI"));

In the above example, I am using Moq, but I want to use NSubstitute.

When I replace Mock.of with Substitute.For, I get the below error:

services.AddSingleton(Substitute.For<IWebHostEnvironment>(w =>
 w.EnvironmentName == "Development" &&
 w.ApplicationName == "Application.WebUI"));

Error: Cannot convert lambda expression to the type 'object' because it is not of a delegate type.

How should we use Substitute for the above example?

Upvotes: 0

Views: 842

Answers (1)

Julian
Julian

Reputation: 36770

The parameters of the .For are passed as constructor arguments in NSubstitute. That could be useful for substituting classes with virtual members.

enter image description here

See also the code of Substitute

public static T For<T>(params object[] constructorArguments) 

The equivalent in NSubstitute for your example:

var env = Substitute.For<IWebHostEnvironment>();
env.EnvironmentName.Returns("Development");
env.ApplicationName.Returns("Application.WebUI");
services.AddSingleton(env);

Upvotes: 2

Related Questions