Automation Integration testing by OWIN to Self-Host ASP.NET Web API
As I tried to implement integration by automation testing at testing the ASP.NET Web API pipeline using its in-memory hosting capabilities. So, I will show how to host ASP.NET Web API, using OWIN to self-host the Web API framework.
First, create a dummy app to test and install a package
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
After that, we will create a dummy ApiController on project WebAPI.
using System.Web.Http;namespace TestExampleOwinStartUp.Controllers
{
public class DemoController : ApiController
{
// GET api/values/5
public string Get(int id)
{
return "value";
}
}
}
Then this being an Owin app, let’s create a Startup class, where we configure the Web API routes
using Owin;
using System.Web.Http;namespace OwinSelfhostSample
{
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); appBuilder.UseWebApi(config); config.MapHttpAttributeRoutes();
config.EnsureInitialized();
}
}
}
And I will run start the OWIN Host and make a request with HttpClient and I use xUnit
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;
using OwinSelfhostSample;
using Xunit;namespace OwinSelfhostSample_test
{
public class UnitTest1
{
[Fact]
public async Task Test1()
{
var baseAddress = "http://localhost:5050/";
var endPoint = "api/demo/1";
HttpResponseMessage response;using (WebApp.Start<Startup>(url: baseAddress))
{
HttpClient client = new HttpClient();
response = await client.GetAsync(baseAddress + endPoint);
}Assert.Equal("OK", response.StatusCode.ToString());}
}
}
So, after I tried to use Owin self-host instance of an in-memory test server per test fixture, and It allows each test to use it to make HTTP calls through the OWIN.
Let’s go to play around on it and I hope your guys will enjoy doing automation testing.