This is a mirror of official site: http://jasper-net.blogspot.com/

How to Mock a WCF Service

| Wednesday, January 25, 2012
Introduction

Unit tests have become integral part of any build now days. Unit tests should be written normally for smallest units of code i.e. methods doing some specific and independent work. But, what if your method is calling different layers (like Method => BusinessLogicLayer =>DataLayer) to get its work done and you want to write unit tests for that? If your unit test also calls all these layers in actual it doesn’t go with the actual purpose of unit tests. Unit test should definitely not call other layers for sure. Situation becomes a bit tricky and difficult when you want to write a unit test for a method which calls a WCF service internally.

To overcome from this problem we use Mock Frameworks. There are many Mock frameworks available in the market but I will be discussing mocking using MOQ here. Let us take wcf scenario and try to mock a wcf method using MOQ mock framework while writing a unit test for wcf client method (which calls wcf service).

I will highlight some other features also later in this article.

Using the Code

My wcf service WCFService is derived from an interface IWCFService and has a method GetData(int value)

namespace WCFService
{

    public class WCFService : IWCFService

    {
        public string GetData(int value)

        {
            return string.Format("You entered: {0}", value);

        }

    }
}

A wcf client WCFClient consumes WCFService using a service agent WCFServiceAgent. Service agent implements a method HitWCFService() which calls service method GetData()


namespace WCFClient
{
    public class WCFServiceAgent

    {
        IWCFService wcfService;

        public WCFServiceAgent()
        {

            this.wcfService = new WCFServiceClient();
        }

        // constructor for unit test
        public WCFServiceAgent(bool isUnitTest)

        {
            this.wcfService = UnityHelper.IoC.Resolve<IWCFService>();

        }

Read more: Codeproject
QR: How-to-Mock-a-WCF-Service

Posted via email from Jasper-net

0 comments: