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

1 Answer 1

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>();
Sign up to request clarification or add additional context in comments.

5 Comments

i used var service = (IMyService)_server.Host.Services.GetService(typeof(IMyService));
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)
ahh its extension method.:) thats why i couldn't find it on _server.Host.Services that helped
Hitting Ctrl+. on the error would told you how to resolve it :P
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.