Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving dependencies in Integration test in ASP.NET Core

I have ASP.NET Core API. I have already gone through documentation here that shows how to do integration testing in asp.net core. The example sets up a test server and then invoke controller method.
However I want to test a particular class method directly (not a controller method)? For example:

  public class MyService : IMyService
  {
      private readonly DbContext _dbContext;

      public MyService(DbContext dbContext)
      {
          _dbContext = dbContext;
      }

      public void DoSomething()
      {
          //do something here
      }             
  }

When the test starts I want startup.cs to be called so all the dependencies will get register. (like dbcontext) but I am not sure in integration test how do I resolve IMyService?

Note: The reason I want to test DoSomething() method directly because this method will not get invoked by any controller. I am using Hangfire inside this API for background processing. The Hangfire's background processing job will call DoSomething() method. So for integration test I want to avoid using Hangfire and just directly call DoSomething() method

like image 927
LP13 Avatar asked Apr 17 '17 17:04

LP13


1 Answers

You already have a TestServer when you run integration tests, from here you can easily access the application wide container. You can't access the RequestServices for obvious reason (it's only available in HttpContext, which is created once per request).

var testServer = new TestServer(new WebHostBuilder()
    .UseStartup<Startup>()
    .UseEnvironment("DevelopmentOrTestingOrWhateverElse"));

var myService = testServer.Host.Services.GetRequiredService<IMyService>();
like image 197
Tseng Avatar answered Oct 22 '22 21:10

Tseng