Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get service from WebApplicationFactory<T> in ASP.NET Core integration tests

I want to set up my tests using WebApplicationFactory<T> as detailed in Integration tests in ASP.NET Core.

Before some of my tests I need to use a service configured in the real Startup class to set things up. The problem I have is that I can't see a way to get a service from the factory.

I could get a service from factory.Server using factory.Host.Services.GetRequiredService<ITheType>(); except that factory.Server is null until factory.CreateClient(); has been called.

Is there any way that I am missing to get a service using the factory?

Thanks.

like image 251
Simon Vane Avatar asked Oct 10 '18 17:10

Simon Vane


2 Answers

You need to create a scope from service provider to get necessary service:

using (var scope = AppFactory.Server.Host.Services.CreateScope()) {     var context = scope.ServiceProvider.GetRequiredService<MyDatabaseContext>(); } 
like image 181
Alexey Starchikov Avatar answered Sep 21 '22 10:09

Alexey Starchikov


Please pardon me. I know you ask for Net Core 2.1, but since v3.1+ people got here as well...

My project uses Net Core 3.1. When I use AppFactory.Server.Host.Services.CreateScope() like Alexey Starchikov's suggestion, I encounter this error.

The TestServer constructor was not called with a IWebHostBuilder so IWebHost is not available. 

Noted here, by designs.

So I use the below approach. I put database seeding in the constructor of the test class. Note that, I do not have to call factory.CreateClient(). I create client variables in test methods as usual.

using (var scope = this.factory.Services.CreateScope()) {     var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();      // Seeding ...      dbContext.SaveChanges(); } 
like image 33
Lam Le Avatar answered Sep 18 '22 10:09

Lam Le