How to easily test WCF Web Api services
Given the many cross-cutting concerns you can cover using the new Web API pipeline, it’s not a bad idea to have a bunch of integration-style tests that cover the actual running service end to end.
This is pretty straightforward nowadays: create the service host, open, close on cleanup. Add the Http host configuration from the new APIs on top and that’s about it.
The following code is using a little helper class (in the spirit of a true NETFx nuget) that makes this slightly easier:
[Fact]
public void WhenHostingService_ThenCanInvokeIt()
{
using (var webservice = new HttpWebService<TestService>(
serviceBaseUrl: "http://localhost:20000",
serviceResourcePath: "test",
serviceConfiguration: HttpHostConfiguration.Create()))
{
var client = new HttpClient(webservice.BaseUri);
// Builds: http://localhost:2000/test/23
var uri = webservice.Uri("23");
var response = client.Get(uri);
Assert.True(response.IsSuccessStatusCode, response.ToString());
Assert.True(response.Content.ReadAsString().Contains("23"));
}
}...