Wrote prototype in-memory end-to-end unit tests on Web API so that these tests can be run on TFS after checkin. Thanks for the articles about in-memory web server and sample tests.

[TestMethod]
public void InMemoryEndToEndWebAPITest()
{
  // Arrange
  var expectedJasonResult = "...";
  var config = new HttpConfiguration();
  YourWebAPIProject.WebApiConfig.Register(config);
  using (var server = new HttpServer(config))
  {
    var client = new HttpClient(server);
    string url = "http://localhost:60000/api/values/"; 
    var request = new HttpRequestMessage
    {
      RequestUri = new Uri(url),
      Method = HttpMethod.Get
    };
    request.Headers.Accept.Add(
      new MediaTypeWithQualityHeaderValue("application/json"));

    // Act
    using (var response = client.SendAsync(request))
    {
      // Assert
      Assert.AreEqual(HttpStatusCode.OK, response.Result.StatusCode);  
      Assert.AreEqual(expectedJasonResult,
        response.Result.Content.ReadAsStringAsync().Result);
    }
  }
}

 

References:

https://stackoverflow.com/questions/37475387/unit-testing-integration-testing-web-api-with-httpclient-in-visual-studio-2013

https://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/

Advertisements