How can I use IConfiguration from my integration tests?

后端 未结 2 1382
感情败类
感情败类 2020-12-17 01:46

I have an API, and I\'m trying to make some integration tests for it with XUnit. Here\'s my API controller constructor:

public class MyController : Controlle         


        
2条回答
  •  执笔经年
    2020-12-17 02:03

    I think it's better to use dependency injection in your test project; for future use.

    In your test project:

    1. Add a new appsettings.json file to your test project with all the configurations you need.
    2. Install the package: Microsoft.Extensions.DependencyInjection.
    3. Create a class for the test setup; for instance TestSetup.cs.

      public class TestSetup
      {
          public TestSetup()
          {
              var serviceCollection = new ServiceCollection();
              var configuration = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile(
                       path: "appsettings.json",
                       optional: false,
                       reloadOnChange: true)
                 .Build();
              serviceCollection.AddSingleton(configuration);
              serviceCollection.AddTransient();
      
              ServiceProvider = serviceCollection.BuildServiceProvider();
          }
      
          public ServiceProvider ServiceProvider { get; private set; }
      }
      
    4. In your test class; I am using Xunit

      public class MyControllerTest: IClassFixture
      {
          private ServiceProvider _serviceProvider;
          private MyController _myController;
      
          public MyControllerTest(TestSetup testSetup)
          {
             _serviceProvider = testSetup.ServiceProvider;
             _myController = _serviceProvider.GetService();
          }
      
          [Fact]
          public async Task GetUserShouldReturnOk()
          {
              var result = await _myController.GetUser(userId);
              Assert.IsType(result);
          }
      
      }
      

提交回复
热议问题