Dependency injection in Xunit project
Solution 1
You can implement your own service provider to resolve DbContext
.
public class DbFixture
{
public DbFixture()
{
var serviceCollection = new ServiceCollection();
serviceCollection
.AddDbContext<SomeContext>(options => options.UseSqlServer("connection string"),
ServiceLifetime.Transient);
ServiceProvider = serviceCollection.BuildServiceProvider();
}
public ServiceProvider ServiceProvider { get; private set; }
}
public class UnitTest1:IClassFixture<DbFixture>
{
private ServiceProvider _serviceProvider;
public UnitTest1(DbFixture fixture)
{
_serviceProvider = fixture.ServiceProvider;
}
[Fact]
public void Test1()
{
using (var context = _serviceProvider.GetService<SomeContext>())
{
}
}
}
But bear in your mind using EF inside a unit test is not a good idea and it's better to mock DbContext.
The Anatomy of Good Unit Testing
Solution 2
You can use Xunit.DependencyInjection
Bob5421
Updated on October 04, 2021Comments
-
Bob5421 over 2 years
I am working on an ASP.Net Core MVC Web application.
My Solution contains 2 projects:
- One for the application and
- A second project, dedicated to unit tests (XUnit).
I have added a reference to the application project in the Tests project.
What I want to do now is to write a class in the XUnit Tests project which will communicate with the database through entity framework.
What I was doing in my application project was to access to my
DbContext
class through constructor dependency injection.But I cannot do this in my tests project, because I have no
Startup.cs
file. In this file I can declare which services will be available.So what can I do to get a reference to an instance of my
DbContext
in the test class?