1

私はwebapiをテストするためにunittestingプロジェクトを作っています。コントローラーを初期化する必要があるのは、コンストラクターでdependency-injectionによって提供され、うまく動作するIConfigurationを受け取ることです。asp.netコアでIConfigurationのインスタンスを取得するには?

しかし、手動で初期化したいときは、このインスタンスを取得する方法がありません。

私は同じプロジェクトの内部にunittestプロジェクトから初期化しようとしています。

コントローラは次のようになります。

public Controller(IConfiguration configuration) { _configuration = configuration; } 

答えて

2

私はおそらくネットCoreアプリケーションで、あなたのコントローラや他のクラスにIConfigurationのインスタンスを渡すべきではないことを声明から始めるべきであると思います。 IOtions<T>によって厳密に型指定された設定を使用する必要があります。詳細はOptions pattern in ASP.NET Coreこちらの記事をご覧ください。

オプションパターンを使用する場合は、コントローラが必要とする設定にPOCOがあります。この設定は、その後IOptions<T>に包まれたコントローラに注入されたオブジェクト:

public class ControllerSettings 
{ 
    public string Setting1 { get; set; } 

    public int Setting2 { get; set; } 

    // ... 
} 

public class Controller 
{ 
    private readonly ControllerSettings _settings; 

    public Controller(IOptions<ControllerSettings> options) 
    { 
     _settings = options.Value; 
    } 
} 

その後、それはあなたがユニットテストから好きな設定を渡すために非常に簡単です。ただ、設定インスタンスを記入し、MoqまたはNSubstituteのように、可能なモックフレームワークのいずれかとIOptions<T>にラップ:

[TestMethod] 
public void SomeTest() 
{ 
    var settings = new ControllerSettings 
    { 
     Setting1 = "Some Value", 
     Setting2 = 123, 
    }; 

    var options = new Mock<IOptions<ControllerSettings>>(); 
    options.Setup(x => x.Value).Returns(settings); 

    var controller = new Controller(options.Object); 

    // ... 
} 

時には統合テストを開発するとき、たとえば、プロジェクトの実際の構成を使用することが必須です。この場合、ConfigurationBuilderのインスタンスを作成し、テストされたコードと同じ設定ソースで入力することができます。

IConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); 
// Duplicate here any configuration sources you use. 
configurationBuilder.AddJsonFile("AppSettings.json"); 
IConfiguration configuration = configurationBuilder.Build(); 
関連する問題