Selfhost a WCF service for testing

Selfhost a WCF service for testing

17 January 2015

I have been spoilt with Microsoft.OWIN.Testing with my recent Web Api work.
Whenever I start to maintain some WCF applications missing tests I find myself thinking; there must be a way to self-host and test this.

This is a very short guide to test a self-hosted WCF application based on my experience.

The test

The test below simply checks to make sure that the text Hello World is returned in the the response body.

/// <summary>
/// Simple test that just sees if 'Hello World' is returned.
/// </summary>
public void ShouldSayHelloWorld()
    using (Host.OpenSimpleHelloWorldService(baseUri))
        var resourceUri = new Uri(baseUri, "hello");
        var request = WebRequest.Create(resourceUri);
        using (var sr = new StreamReader(request.GetResponse().GetResponseStream()))
            Assert.Equal("Hello World",sr.ReadToEnd());

The HelloWorldService

Below you will find simple code which returns Hello World.

class HelloWorldService : IHelloWorldService
    public Stream GetHello()
        var ms = new MemoryStream();
        var sw = new StreamWriter(ms);
        sw.Write("Hello World");
        ms.Seek(0, 0);
        return ms;

The self hosting

Below is some code I have pieced together from the sample code.

var serviceHost = new ServiceHost(typeof(HelloWorldService));
var endpoint = serviceHost.AddServiceEndpoint(typeof(IHelloWorldService), new WebHttpBinding(), baseUri);
endpoint.Behaviors.Add(new WebHttpBehavior());
serviceHost.Open();  // remember to call serviceHost.Close() when you're done.

You will need to launch Visual Studio with escalated privileges.

Download my WCF Research sample

Feel free to download my WCF Research Source Code.

.NET SelfHost Testing WCF XUnit