.NET Core Unit Testing - Mock IOptions

前端 未结 8 902
难免孤独
难免孤独 2020-12-12 17:55

I feel like I\'m missing something really obvious here. I have classes that require injecting of options using the .NET Core IOptions pattern(?). When I unit te

8条回答
  •  甜味超标
    2020-12-12 18:20

    Agree with Aleha that using a testSettings.json configuration file is probably better.

    And then, instead of injecting the IOption, you can simply inject the real SampleOptions in your class constructor, when unit test the class, you can do the following in a fixture or again just in the test class constructor:

    var builder = new ConfigurationBuilder()
        .AddJsonFile("testSettings.json", true, true)
        .AddEnvironmentVariables();
    
    var configurationRoot = builder.Build();
    configurationRoot.GetSection("SampleRepo").Bind(_sampleRepo);
    

提交回复
热议问题