http://blogs.clariusconsulting.net/kzu

Daniel Cazzulino's Blog

Go Back to
kzu′s Latest post

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"));
    }
}

That is in fact the unit test that shows that it works and how it’s used Smile. It’s available already in the NuGet repository, or just search for WebApi.Testing in the Library Package Reference dialog in VS (first reference was its old name, provided for backwards compatibility):

image

 

Enjoy!

Comments

6 Comments

  1. How does this differ from, ie. the WebServiceHost object ?

  2. ’cause this knows how to run the Web Api pipeline?

  3. I use the application of “wcftestclient.exe”

  4. Hi there. Nice post.
    Your project for testing WCF Web Api is not avaliable anymore on NuGet or Codeplex.
    Can you point me to source code ?
    Is this compatible with latest version of WCF Web Api ?

  5. I didn’t see the package on NuGet either. Is there an update?