.NET core: 在TestServer整合測試中取得注入的Service

在.NET core利用TestServer來整合測試時如何取得注入的服務, 以EFCore DbContext為例

首先在整合測試用的StartUp.cs裡注入DbContext

  internal class StartUpForTest
  {
    ...
    
    /// <summary>
    ///  This method gets called by the runtime. Use this method to add services to the container.
    /// </summary>
    /// <param name="services">The services.</param>
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc();
      services.AddDbContext<MyDbContext>(options => options.UseInMemoryDatabase("MyDb"));
    }
    
    ...

  }

利用TestServer.Host.Services.GetServie(TypeOf(MyDbContext))取得在StartUp注入的DbContext, 接著就在test case中使用了

  ...
  using Xunit

  public class ControllerTests
  {
    private readonly TestServer _testServer;
    private readonly HttpClient _client;
    private readonly TimestealerContext _context;

    public ControllerTests()
    {
      _testServer = new TestServer(new WebHostBuilder().UseStartup<StartUp>());
      _client = _testServer.CreateClient();
      _context = _testServer.Host.Services.GetService(typeof(TimestealerContext)) as TimestealerContext;
    }

    ...
  }