locked
Override settings used in ConfigureServices, in integration tests RRS feed

  • Question

  • User-1092841962 posted

    During Startup, in ConfigureServices, I need to access a property from appsettings.json.
    I'd like to have it typed, so I'm using the Options pattern.
    To retrieve the value, I do this;

    public void ConfigureServices(IServiceCollection services)
    {
    ...
    var jwtOptions = configuration.GetSection("Jwt").Get<JwtOptions>();
    // then use jwtOptions.MyProperty
    ...
    }

    The option class looks like this:

    public class JwtOptions
    {
       public string? MyProperty { get; set; }
    }

    When debugging, all works fine and it gets the correct value from the config file.

    Now I want to override the value from the config file during integration tests.
    I'm creating my HttpClient like this and overriding the options value in the ConfigureTestServices method.

    var client = webAppFactory.WithWebHostBuilder(builder =>
    {
       builder.ConfigureTestServices(services =>
       {
          services.Configure<JwtOptions>(opts =>
          {
             opts.MyProperty= "Test value";
          });
       });
    })
    .CreateClient(new WebApplicationFactoryClientOptions());

    Note: I'm using the Startup file from the webproject when creating the webAppFactory, not using any inheritance.

    Unfortunately, the value doesn't get overriden when running the test and the configuration value retrieved is the one that's the web project's appsettings.json file.

    What am I doing wrong?

    Friday, May 8, 2020 11:25 AM

Answers

All replies