Home > other >  How to mock parameter provided as input to anonymous Func delegate via lambda expression?
How to mock parameter provided as input to anonymous Func delegate via lambda expression?

Time:05-27

I have this code for which I'm trying to write a unit test:

public static void AddRuntimeServices(this IServiceCollection services)
{
    services.AddScoped<IAppClient>((serviceProvider) =>
    {
        var snapshotService = serviceProvider.GetRequiredService<ISnapshotService>();
        var urlContext = serviceProvider.GetRequiredService<IUrlContext>();

        return new AppClient(
            serviceUrl: urlContext.restApiUrl,
            httpClient: snapshotService.Client);
    });
}

In this code, I can mock the services input given to this method, but how do I mock the serviceProvider variable (that comes from within the services input given to this method), that's given as an input into an anonymous Func delegate that's being written inline ?

I want to be able to mock serviceProvider, so that I can write something like this:

serviceProvider.GetRequiredService<ISnapshotService>().Returns(somethingToReturn);

I'm using MSTest (Microsoft.VisualStudio.TestTools.UnitTesting) to write my unit tests.

CodePudding user response:

Use an actual service collection. and add the mocked services so that when it resolves them you have control of the desired behavior

//...

//Arrange

IServiceCollection services = new ServiceCollection();

ISnapshotService snapshotService = Mock.Of<ISnapshotService>();
IUrlContext urlContext = Mock.Of<IUrlContext>();

services.AddScoped<ISnapshotService>(sp => snapshotService);
services.AddScoped<IUrlContext>(sp => urlContext);

//Act
services.AddRuntimeServices();

IServiceProvider serviceProvider = services.BuildServiceProvider();
IAppClient client = serviceProvider.GetRequiredService<IAppClient>();

//Assert
//...assert expected behavior

//...
  • Related