2016-07-01 18 views
6

現在、プロジェクトを.NET Core RC1から新しいRTM 1.0バージョンにアップグレードしています。 RC1では、RC1ではバージョンでIHostingEnvironment 1.0ユニットテストでIHostingEnvironmentを設定します

に置き換えたIApplicationEnvironmentが、私はこの

public class MyClass 
{ 
    protected static IApplicationEnvironment ApplicationEnvironment { get;private set; } 

    public MyClass() 
    { 
     ApplicationEnvironment = PlatformServices.Default.Application; 
    } 
} 

を行うことができなかった誰もがv1.0の中でこれを達成する方法を知っていますか?

public class MyClass 
{ 
    protected static IHostingEnvironment HostingEnvironment { get;private set; } 

    public MyClass() 
    { 
     HostingEnvironment = ???????????; 
    } 
} 
+1

あなただけのインターフェイスを実装することにより、ユニットテストでそれを模擬可能性ができます。 –

答えて

1

一般に、IHostingEnvironmentは単なるインターフェイスなので、単純に偽装して必要なものを返すことができます。

テストでTestServerを使用している場合は、WebHostBuilder.Configureメソッドを使用することをお勧めします。このような何か:

var testHostingEnvironment = new MockHostingEnvironment(); 
var builder = new WebHostBuilder() 
      .Configure(app => { }) 
      .ConfigureServices(services => 
      { 
       services.TryAddSingleton<IHostingEnvironment>(testHostingEnvironment); 
      }); 
var server = new TestServer(builder); 
+0

私はTestServerクラスを使いたくありません。それは私が信じている統合テストのためのものです。私は、アプリケーションの完全なインスタンスをスピンアップする必要はありません。私はちょうど特定のクラスをテストしたい。私が持っているのは、RC1で 'ApplicationEnvironment'を使ったテスト基底クラスですが、1.0でそれを簡単に置き換えることはできません。 –

+0

なぜそれを嘲笑したくないのですか? HostingEnvironment = <あなたのIHostingEnvironmentの模擬実装> – Set

5

あなたが必要な場合はモックフレームワークを使用してIHostEnvironmentを模擬またはインタフェースを実装することで、偽のバージョンを作成することができます。

このようなクラスを与える...

public class MyClass { 
    protected IHostingEnvironment HostingEnvironment { get;private set; } 

    public MyClass(IHostingEnvironment host) { 
     HostingEnvironment = host; 
    } 
} 

セットアップ部品番号を使用してユニットテストの例は...

public void TestMyClass() { 
    //Arrange 
    var mockEnvironment = new Mock<IHostingEnvironment>(); 
    //...Setup the mock as needed 
    mockEnvironment 
     .Setup(m => m.EnvironmentName) 
     .Returns("Hosting:UnitTestEnvironment"); 
    //...other setup for mocked IHostingEnvironment... 

    //create your SUT and pass dependencies 
    var sut = new MyClass(mockEnvironment.Object); 

    //Act 
    //...call you SUT 

    //Assert 
    //...assert expectations 
} 
関連する問題