Search code examples
c#mediatr

automate test for mediatR in dot net


hi guys I want write unit test for structure of MediatR.after search on internet I found that there is nothing library for this one. How can I test it? (unit test)


Solution

  • I'm not sure what testing framework is being used, and I hope this might help.

    But with NUnit, you can try something like this using the MediatR NuGet package. The code below needs to be in the test setup.

    public static async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
    {
        using var scope = _scopeFactory.CreateScope();    
        var mediator = scope.ServiceProvider.GetRequiredService<ISender>();    
        return await mediator.Send(request);
    }
    

    And then in the unit test just use:

      await this.SendAsync(commandThatNeedsToBeSent);
    

    You can clean up the method body, by using the resolve to get the service. Found a repository that might be really neat. All credit goes to the author of the repository.

    https://github.com/jasontaylordev/CleanArchitecture/blob/main/tests/Application.IntegrationTests/Testing.cs