Microsoft Technology, .Net, BizTalk, Sharepoint & etc.

Liedong(Ken) Zheng, Senior SharePoint Developer at SIMPLOT

Posts Tagged ‘MOQ’

MOQ WCF

Posted by ken zheng on September 9, 2008

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

Posted in .Net, VS2008 | Tagged: , | Leave a Comment »

MOQ YOUR CODE

Posted by ken zheng on September 9, 2008

MOQ is a very useful mocking library available to mock your code, and doesn’t require any prior knowledge or experience with mocking concepts.

You can download DLL from http://code.google.com/p/moq/
Below is the example I created to demo simple MOQ:
First, I created a couple of business classes

    public class Emailer
    {
        private IEmailService EmailService { get; set; }

        public Emailer(IEmailService emailService)
        {
            EmailService = emailService;
        }

        public void SendBatchEmails()
        {
            Dictionary<string, string> emails = new Dictionary<string, string>
                                                    {
                                                        {"foo1@hotmail.com","foo1"},
                                                        {"foo2@hotmail.com","foo2"},
                                                        {  "foo3@hotmail.com","foo3"}
                                                    };
            foreach (KeyValuePair<string, string> email in emails)
            {
                if (!EmailService.SendEmail(email.Key, email.Value))
                {
                    throw new ApplicationException("Some message here");
                }
            }

        }
    }

    public class EmailService: IEmailService
    {
        public bool SendEmail(string emailAddress, string message)
        {
            return false;
        }
    }

    public interface IEmailService
    {
        bool SendEmail(string emailAddress, string message);
    }

The code is quite straightforward. Now right click on the code and select “Create a Unit Test” from the context menu. A new test class is created. Create the first test method

        [TestMethod()]
        public void NonMock()
        {
            var emailService = new EmailService();
            var emailer = new Emailer(emailService);

            emailer.SendBatchEmails();

        }

It seems do the job but actually there are a couple of issues. The first issue is this is not really Unit Test but integration test, the second one is the test method will fail as SendEmail will return false so an exception is thrown. Now we need MOQ to help us mocking the EmailService

public void TestWithMock()
        {
            var mockEmailService = new Mock<IEmailService>();
            mockEmailService.Expect((x=>x.SendEmail(It.IsAny<string>(),It.IsAny<string>()))).Returns(true);

            var emailer = new Emailer(mockEmailService.Object);
            emailer.SendBatchEmails();

            mockEmailService.VerifyAll();
        }

So the above code is mock the IEmailService, It.IsAny() means we don’t care about the string and the method return true. When pass the MOCK obhect remember use mockEmailService.Object. and mockEmailService.VerifyAll();

Below code is how to test if the expected exception when SendEmail return false and exception thrown from EmailService

        /// <summary>
        ///A test for Mock which return false,
        /// expected exception thrown
        ///</summary>
        [TestMethod()]
        [ExpectedException(typeof(ApplicationException), "Some message here")]
        public void TestWithMock_ReturnFalse()
        {
            var mockEmailService = new Mock<IEmailService>();
            mockEmailService.Expect((x => x.SendEmail(It.IsAny<string>(), It.IsAny<string>()))).Returns(false);

            var emailer = new Emailer(mockEmailService.Object);
            emailer.SendBatchEmails();

            mockEmailService.VerifyAll();
        }

        /// <summary>
        ///A test for Mock which throw exception,
        ///
        ///</summary>
        [TestMethod()]
        [ExpectedException(typeof(ApplicationException), "Some message here")]
        public void TestWithMock_ThrowException()
        {
            var mockEmailService = new Mock<IEmailService>();
            mockEmailService.Expect((x => x.SendEmail(It.IsAny<string>(), It.IsAny<string>()))).Throws(new ApplicationException("AA"));

            var emailer = new Emailer(mockEmailService.Object);
            emailer.SendBatchEmails();

            mockEmailService.VerifyAll();
        }

You can download code from Here

Posted in .Net, VS2008 | Tagged: , , | Leave a Comment »