2016-07-01 10 views
6

Attualmente sto aggiornando un progetto da .NET Core RC1 alla nuova versione RTM 1.0. In RC1, c'era un IApplicationEnvironment che è stato sostituito con IHostingEnvironment nella versione 1.0Impostare l'IHostingEnvironment nel test dell'unità

In RC1 ho potuto fare questo

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

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

Qualcuno sa come raggiungere questo obiettivo in v1.0?

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

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

Si potrebbe semplicemente deridere nel test di unità implementando l'interfaccia . –

risposta

1

In generale, come IHostingEnvironment è solo un'interfaccia, puoi semplicemente deriderlo per restituire quello che vuoi.

Se si utilizza TestServer nei test, il modo migliore per simulare è utilizzare il metodo WebHostBuilder.Configure. Qualcosa di simile a questo:

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

Non voglio usare la classe TestServer. Questo è più per il test di integrazione, credo. Non ho bisogno di creare un'istanza completa dell'app. Voglio solo testare una particolare classe. Quello che ho è una classe base di test che ha usato 'ApplicationEnvironment' in RC1, ma non riesco a sostituirlo facilmente in 1.0 –

+0

Allora perché non ti piace semplicemente deriderlo? HostingEnvironment = Set

5

È possibile prendere in giro il IHostEnvironment utilizzando un quadro di scherno, se necessario, o creare una falsa versione implementando l'interfaccia.

Dare una classe come questa ...

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

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

È possibile impostare un esempio di test di unità utilizzando Moq ...

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 
} 
Problemi correlati