Is it possible to use Dependency Injection with xUnit?

Rookian picture Rookian · Aug 24, 2016 · Viewed 24.1k times · Source

I have a test class with a constructor that needs an IService.

public class ConsumerTests
{
    private readonly IService _service;
    public ConsumerTests(IService servie)
    {
      _service = service;
    }

    [Fact]
    public void Should_()
    {
       //use _service
    }
}

I want to plugin my DI container of choice to build the test class.

Is this possible with xUnit?

Answer

Hatim picture Hatim · Nov 12, 2019

Yes it's possible with Xunit.DependencyInjection

Install-Package Xunit.DependencyInjection

and you can inject your services

[assembly: TestFramework("Your.Test.Project.Startup", "AssemblyName")]
    
namespace Your.Test.Project
{
    public class Startup : DependencyInjectionTestFramework
    {
        public Startup(IMessageSink messageSink) : base(messageSink) { }
    
        protected override void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient<IDependency, DependencyClass>();
        }
    }
}

https://github.com/pengweiqhca/Xunit.DependencyInjection