I am working on an ASP.Net Core MVC Web application.
My Solution contains 2 projects:
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?
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.
Fact vs Theory In an Xunit test class or fixture, there are two kinds of tests: Fact tests and Theory tests. The small, but very important, difference is that Theory tests are parameterized and can take outside input. Fact tests, however, are not parameterized and cannot take outside input.
It allows you to create new attributes to control your tests. It ensures custom functionality with the possibility of extending the Asset class's Contains, DoesNotContain Equal, NotEqual, InRange, & NotInRange. xUnit also allows you to inherit from Fact, Theory, and other attributes.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With