Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Dependency Injection with xUnit?

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?

like image 808
Rookian Avatar asked Aug 24 '16 19:08

Rookian


People also ask

Can xUnit be used with .NET framework?

The xUnit.net test runner that we've been using supports . NET Core 1.0 or later, . NET 5.0 or later, and . NET Framework 4.5.

Does xUnit have setup?

xUnit.net offers several methods for sharing this setup and cleanup code, depending on the scope of things to be shared, as well as the expense associated with the setup and cleanup code.

Does xUnit run in parallel?

Parallelism in Test FrameworksTests written in xUnit.net version 1 cannot be run in parallel against each other in the same assembly, though multiple test assemblies linked against v1 are still able to participate in the runner parallelism feature described in the next sub-section.

Is xUnit a testing framework?

xUnit is the collective name for several unit testing frameworks that derive their structure and functionality from Smalltalk's SUnit. SUnit, designed by Kent Beck in 1998, was written in a highly structured object-oriented style, which lent easily to contemporary languages such as Java and C#.


1 Answers

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

like image 177
Hatim Avatar answered Sep 22 '22 22:09

Hatim