I really needed to mock and test WCF services for a new project I’m working on. I had heard great things about the Moq mocking framework so I decided to use that.

My goal was to create a service that would know how to talk to a WCF service SoapClient and would also know how to talk to a mocked SoapClient (for testing purpose). This service will contain all our business logic. Finally we can test our service and make sure it’s behaving correctly (using unit tests). Given that, through out our program we will always call that service instead of our WCF service.

I started by creating a Service Reference to my WCF service. My namespace was UserProxy and the service name was UserService.

So to mock the service, I needed to find an interface my WCF service implements – and I found one!

public partial class UserServiceSoapClient : System.ServiceModel.ClientBase<MyProject.UserProxy.UserServiceSoap>, MyProject.UserProxy.UserServiceSoap

As you can see the SOAP client UserServiceSoapClient (which is auto-generated), implements an interface MyProject.UserProxy.UserServiceSoap. So whatever your service name is, just add Soap behind it, and you have found an auto-generated interface that you can use! Now we can mock that!

But first, let’s create a service we will use for talking to our WCF and mocked services. Of course you would want to add some Dispose method that disposes all resources, but I won’t cover that here.

Here’s my UserProxyService

// Remember this, because it's the namespace of your WCF service
using MyProject.UserProxy;

// Service class that can talk to both WCF services and mock service
public class UserProxyService
{
    // WCF service interface
    private UserServiceSoap proxy;

    // Default constructor that creates an instance of our WCF service
    public UserProxyService()
    {
        // MyProject.UserProxy.UserServiceSoapClient
        proxy = new UserServiceSoapClient();
    }

    // Constructor that accepts a WCF service interface
    // (good for mocking and testing)
    // MyProject.UserProxy.UserServiceSoap interface
    public UserProxyService(UserServiceSoap _service)
    {
        proxy = _service;
    }

    // Here we start defining the functions in our WCF service...
    // Note: User, Authenticate, IsAuthenticatedRequest and
    // IsAuthenticatedResponse objects are all defined in
    // MyProject.UserProxy namespace

    // Gets a user based on authentication token
    public User GetUser(Authenticate auth)
    {
        // Here we can do some logic

        return proxy.GetUser(auth);
    }

    // Checks authentication
    public IsAuthenticatedResponse IsAuthenticated(IsAuthenticatedRequest request)
    {
        // Here we can do some logic

        return proxy.IsAuthenticated(request);
    }
}

Now when we want to call our WCF service, we go through this service instead.

Now for the test!

I just created a new Unit Test project and used the built-in .NET Unit Test.

When we test our service above, we’ll use Moq to create a mocked object of the UserServiceSoap interface and use dependency injection to let our service use that object. Both the mocked object and UserServiceSoapClient class implement that interface, so this is what makes it so easy.

Here’s my UserProxyServiceTest

Below I will break it down and explain each part.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using MyProject.Services;
using MyProject.UserProxy;

[TestClass]
public class UserProxyServiceTest
{
    // Our service
    UserProxyService service;

    // Mock object created for the UserServiceSoap interface
    Mock<UserServiceSoap> mock = new Mock<UserServiceSoap>();

    [TestInitialize]
    public void StartUp()
    {
        // Mock GetUser()
        mock.Setup(s =>
            s.GetUser(It.IsAny<Authenticate>())
        )
        .Returns(new User
        {
            ID = 1,
            Name = "John",
            IsEmployee = true
        });

        // Mock IsAuthenticated()
        mock.Setup(s =>
            s.IsAuthenticated(It.IsAny<IsAuthenticatedRequest>())
        )
        .Returns(new IsAuthenticatedResponse
        {
            IsAuthenticatedResult = new Authenticate(),
            username = "john01"
        });

        // New the UserProxyService and inject the mocked service
        service = new UserProxyService(mock.Object);
    }

    [TestCleanup]
    public void CleanUp()
    {
        // Clean up resources
    }

    [TestMethod]
    public void TestGetUser()
    {
        var temp = service.GetUser(new Authenticate());

        Assert.IsInstanceOfType(temp, typeof(User));

        Assert.AreEqual(temp.ID, 1, "User ID is not correct");
        Assert.AreEqual(temp.Name, "John", "User Name is not correct");
        Assert.IsTrue(temp.IsEmployee, "Employee status is not correct");
    }

    [TestMethod]
    public void TestIsAuthenticated()
    {
        var temp = service.IsAuthenticated(new IsAuthenticatedRequest());

        Assert.IsInstanceOfType(temp.IsAuthenticatedResult, typeof(Authenticate));
        Assert.AreEqual(temp.username, "john01");
    }
}

Now let’s break it down

Mock<UserServiceSoap> mock = new Mock<UserServiceSoap>();

Here Moq does its magic. It creates an object that implements UserServiceSoap interface. Then you can tell that object to behave however you like with the .Setup() function.

[TestInitialize]
public void StartUp()

Here I am defining a function that will run each time a test is run. It doesn’t matter what the function name is, only you have to define [TestInitialize] above it.

mock.Setup(s =>
    s.GetUser(It.IsAny<Authenticate>())
)
.Returns(new User
{
    ID = 1,
    Name = "John",
    IsEmployee = true
});

Here you can setup your mocked object. Whenever it gets a call to GetUser() it should return a new User object with ID = 1, Name = "John", IsEmployee = true. It.IsAny<Authenticate>() just means it can accept ANY Authenticate object – as long it’s of type Authenticate.

service = new UserProxyService(mock.Object);

Here I am creating a new instance of my UserProxyService and injecting the mocked WCF object using dependency injection.

[TestCleanup]
public void CleanUp()
{
    // Clean up resources
}

Here I am defining a function that will run each time after a test is run. It doesn’t matter what the function name is, only you have to define [TestCleanup] above it.

[TestMethod]
public void TestGetUser()
{
    var temp = service.GetUser(new Authenticate());

    Assert.IsInstanceOfType(temp, typeof(User));

    Assert.AreEqual(temp.ID, 1, "User ID is not correct");
    Assert.AreEqual(temp.Name, "John", "User Name is not correct");
    Assert.IsTrue(temp.IsEmployee, "Employee status is not correct");
}

Here I am defining a new test for getting a user based on his authentication token. As you can see I call my service with the mock service data I injected previously. * Next I assert that the returned object is of type User (if not, the test will fail). * Next I assert that the returned object property ID is equal to 1 (if not, the test will fail). * Next I assert that the returned object property Name is equal to John (if not, the test will fail). * Finally I assert that object property IsEmployee is true (if not, the test will fail).

That’s all there is to it. Then I run the tests and they all turn green! Hopefully this guide helps some people.

I’m sorry but I’m not a Moq expert. I have only studied .Setup(), .Returns() and .Throws() methods in Moq but there are many other methods you can use to make testing easier. I recommend their Quickstart guide.