IConfiguration.GetValue をモックする方法 質問する

IConfiguration.GetValue をモックする方法 質問する

トップレベル (どのセクションにも属さない) の構成値 (.NET Core の IConfiguration) をモックしようとしましたが、うまくいきませんでした。たとえば、次のいずれも機能しません (NSubstitute を使用していますが、Moq やモック パッケージでも同じだと思います)。

var config = Substitute.For<IConfiguration>();
config.GetValue<string>(Arg.Any<string>()).Returns("TopLevelValue");
config.GetValue<string>("TopLevelKey").Should().Be("TopLevelValue"); // nope
// non generic overload
config.GetValue(typeof(string), Arg.Any<string>()).Returns("TopLevelValue");
config.GetValue(typeof(string), "TopLevelKey").Should().Be("TopLevelValue"); // nope

GetSection私の場合は、この同じ構成インスタンスから呼び出す必要もあります。

ベストアンサー1

メモリ内データを含む実際の構成インスタンスを使用できます。

//Arrange
var inMemorySettings = new Dictionary<string, string> {
    {"TopLevelKey", "TopLevelValue"},
    {"SectionName:SomeKey", "SectionValue"},
    //...populate as needed for the test
};

IConfiguration configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(inMemorySettings)
    .Build();


//...

後は、テストを実行するために、希望通りの構成を使用するだけです。

//...

string value = configuration.GetValue<string>("TopLevelKey");

string sectionValue = configuration.GetSection("SectionName").GetValue<string>("SomeKey");

//...

参照:メモリ構成プロバイダー

おすすめ記事