DNX .Net WebApi Integration testing

I needed to compare some gRPC round trip numbers to plain .Net WebApi. So the question became how to test WepApi round trips from UnitTest harness.

It’s actually pretty simple if you are using the newer DNX libraries. I’m using the TestHost library to get things done.

From project.json

“System.Net.Http”: “4.0.1-beta-23516”,
“Microsoft.AspNet.TestHost”: “1.0.0-rc1-final”,

The UnitTest itself

[Fact]
    public async void PingTheServerRepeat()
    {
      // Setup client & server
      TestServer server = new TestServer(TestServer.CreateBuilder().UseStartup<Startup>());
      HttpClient client = server.CreateClient();

      // Make a request and check response
      var getResponse = await client.GetAsync(“/api/values/5”);
      var response = await getResponse.Content.ReadAsStringAsync();
      Logger.Log(“web api, response=” + response);

      // Hit the webapi, repeatedly
      Stopwatch watch = Stopwatch.StartNew();
      for (int i = 0; i < Util.Repeat; i++)
      {
        getResponse = await client.GetAsync(“/api/values/” + i);
        response = await getResponse.Content.ReadAsStringAsync();
      }
      watch.Stop();
      Logger.Log($“WepApi, round trips={Util.Repeat}, Execution time, millisec={watch.ElapsedMilliseconds}, average roundtrip=” + ((double)watch.ElapsedMilliseconds / Util.Repeat));
      Logger.Log(“web api, response=” + response);

      // Done, release resources
      server.Dispose();
      client.Dispose();
    }

One Comment

  1. […] have changed a bit since the DNX .Net WebApi Integration testing post that I wrote about a year ago. This post will show updated code for .Net Core 1.1, I’m using […]

Leave a Reply