This article shows how to host an entire web API stack in memory for testing using OWIN:
http://www.davidwhitney.co.uk/Blog/2015/01/07/testing-an-asp-net-webapi-app-in-memory/
Whereas this article shows using the OWIN TestServer to unit test controllers:
https://blog.jcorioland.io/archives/2014/04/01/using-owin-to-test-your-web-api-controllers.html
The difference I see is between the use of TestServer.Create
and WebApp.Start<Startup>
What is the key difference and why would you choose one over the other?
Is it simply the difference between unit testing controller methods as web api calls versus end-to-end integration testing in memory?
Using the unit test host. To work with the OWIN Unit Test host, you have to install the NuGet package Microsoft.Owin.Testing in your test project : Once the package is installed, it is possible to create a test server that will host your web api without running IIS. To do that, you have to create an OWIN configuration class in the projet.
OWIN allows web apps to be decoupled from web servers. It defines a standard way for middleware to be used in a pipeline to handle requests and associated responses. ASP.NET Core applications and middleware can interoperate with OWIN-based applications, servers, and middleware.
As you can see in the sample bellow, the HttpClient takes an custom handler that is provided by the OWIN test server. This is this step that allows us to bypass the use of the http protocol and that allows the tests to run without IIS.
Another example of how OWIN-based servers' features can be leveraged by ASP.NET Core is access to features like WebSockets. The .NET OWIN web server used in the previous example has support for Web Sockets built in, which can be leveraged by an ASP.NET Core application.
When you do
TestServer.Create<Startup>()
- you start just the in-memory instance using your startup file. The HttpClient that is inside TestServer is enough for integration testing in-memory. We are starting all the testservers inside one process, so this is not a limitation (currently 4 test servers are running together).
When you do
WebApp.Start<Startup>(Settings.WebApiUrl)
- you start a web app on the url you provide. There is also another overload which accepts options: both urls and settings.
We are using this option only for specific cases. Such as:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With