Webapplicationfactory is a new feature of the ASP. NET Core 2.1 new features MVC functional test infrastructure, which encapsulates the use of testserver, allowing ASP. Integration testing is simpler and more flexible to configure.
Experience today in a real project and simply record it in this blog post.
Modify the. csproj project file where the integration test is located, and the SDK to be set to Microsoft.NET.Sdk.Web
<Sdk= "Microsoft.NET.Sdk.Web">
Add a NuGet package reference for MICROSOFT.ASPNETCORE.APP
<Include= "Microsoft.AspNetCore.App"/>
Add Microsoft.AspNetCore.Mvc.Testing's NuGet package reference, webapplicationfactory in it
<Include= "Microsoft.AspNetCore.Mvc.Testing" Version= "2.1.0" />
Integrated test class implements Iclassfixture<webapplicationfactory<startup>> interface
Public class Webapitest:iclassfixture<webapplicationfactory<startup>>{}
This is webapplicationfactory, which enables the Iclassfixture interface to automatically depend on the type specified in the injected iclassfixture generic in the constructor of the test class.
With Webapplicationfactory, you can create a HttpClient instance directly with it, with the following code:
Public class Webapitest:iclassfixture<webapplicationfactory<startup>>{ private ReadOnly HttpClient _httpclient; Public Webapitest (webapplicationfactory<startup> Factory) { = factory. CreateClient (); }}
This is the code that was not previously webapplicationfactory.
Public class webapitest{ privatereadonly HttpClient _httpclient; Public webapitest () { new webhostbuilder ( ). TestServer. Usestartup<startup>()) . CreateClient (); }}
The simple example code above is just a small test sledgehammer, and Webapplicationfactory is more powerful by inheriting it to rewrite the Configurewebhost () method to configure the webhost
Public class Customwebapplicationfactory<tstartup> : webapplicationfactory<Startup>{ protected Override void configurewebhost (iwebhostbuilder builder) { = = { //... }); }}
Learning ASP. NET Core 2.1: Using Webapplicationfactory in integration testing