Resolving dependencies in Integration test in ASP.NET Core
Asked Answered
P

1

5

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

Partain answered 17/4, 2017 at 17:23 Comment(0)
G
11

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>();
Grizelda answered 17/4, 2017 at 17:34 Comment(5)
i used var service = (IMyService)_server.Host.Services.GetService(typeof(IMyService));Partain
That's the same, the extension methods are just more convenient as you don't need to cast or do any null-checks (`GetRequiredService throws if service can't be resolved, hence the Required in its name)Grizelda
ahh its extension method.:) thats why i couldn't find it on _server.Host.Services that helpedPartain
Hitting Ctrl+. on the error would told you how to resolve it :PGrizelda
this is no a universal approach. You may have no webhost builder, while it's a library with repositories and knows nothing about web, startup file and so on. But it still should be tested.Kilan

© 2022 - 2024 — McMap. All rights reserved.