Tags

,

Here is the example you can mock a WCF service for Unit Testing

Create a simple WCF Service in VS 2008, learn more WCF from http://msdn.microsoft.com/en-au/magazine/cc163289.aspx

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }

Then create a client class which reference the service

    public class HelloMOQ
    {
        
        public string getMessage(MyService.IService1 _service)
        {
            string s = "";
            s = _service.GetData(12);

            return s;
        }
    }

Now it is the time to MOCK, same way to create a Unit Test Project

        [TestMethod()]
        public void getMessageTest()
        {
            var WCFClient = new Mock<IService1>();
            WCFClient.Expect(client => client.GetData(1)).Returns("Hello 1");

            HelloMOQ sc = new HelloMOQ();
            sc.getMessage(WCFClient.Object);
        }

It is easy, doesn’t it.

You can download the source code from Here

Advertisements