0

I have a test project testing various parts of a large 13 project solution. A lot of these tests require database access (wired to a test DB) and numerous services to work. Currently all my test classes inherit from a common BaseTest class which registers DI by calling the following code in the BaseTest constructor :

public IHostBuilder CreateHostBuilder(string[] args = null) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog()
        .ConfigureServices((hostContext, services) =>
        {
            //Omitted for brevity

            _mediator = _provider.GetService<IMediator>();
        });

This works perfectly but I suspect it's needlessly being called by every test class. Is there an equivalent to Program.cs or some sort of way the test project could call this code ONCE? Where can I move this code to from the base constructor to achieve this?

Martin
  • 1,977
  • 5
  • 30
  • 67
  • 2
    Check out https://stackoverflow.com/questions/50921675/dependency-injection-in-xunit-project -- There are answers here that cover both setting up a fixture as well as options like [Xunit.DependencyInjection](https://github.com/pengweiqhca/Xunit.DependencyInjection) for pairing the DI container with unit tests, if you were using XUnit, for example. The solution will largely depend on the test framework you're using. – Adam Oct 22 '21 at 15:53
  • I am using Microsoft.VisualStudio.TestTools.UnitTesting – Martin Oct 22 '21 at 17:01

1 Answers1

0

I ended up switching to XUnit. Much more feature-rich and the xUnit.DependencyInjection nuget package supports dependency injection directly with Startup.cs as we are used to and picks it right up with no additional configuration :

public class Startup
{
    public static void ConfigureHost(IHostBuilder hostBuilder)
    {
        hostBuilder.UseSerilog();
    }

    public static void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ISomeService, SomeService>();
        //...
    }
}
Martin
  • 1,977
  • 5
  • 30
  • 67