Friday, February 17, 2012

Moq and Visual Studio 2010


       In TDD process, we often need to create a "fake" object has the same behaviors as a certain type. Creating a bunch of mock classes is a considerable workload. Fortunately, there are some mocking libraries can create the mock object for us. Moq is one of popular mocking libraries on .Net platform.

       To use Moq in your project, you can either download it from http://code.google.com/p/moq and add Moq.dll into your project reference or install it by menu "Tools"->"Library Package Manager"->"Add Library Package Reference". I would like to provide a simple example to introduce using Moq in .Net.

       Suppose you have a class named Man and an interface name IDevice:

       public interface IDevice

       {

              public bool detect(string s);

       }

       public class Man

       {

              private IDevice device;

              public string TestData { get; set;}

              public Man(IDevice _device) { device = _device; }

              public bool testTheField()

              {

                     return device.detect(TestData);

              }

       }

       Use Moq in your test method:

       // Create a Mock instance setting the interface you want to mock

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

       // Setup the mock instance's behaviour

       mock.Setup(x => x. detect ("ping")).Returns(true);

       // Use the mock object

       Man man = new Man(mock.Object);

       man.TestData = "ping";

       bool testResult = man.testTheField();

       // Assert the result must be true

       Assert.AreEqual(testResult, true);

       As you can see, you don't have to create a mock class to implement the IDevice's behaviour to test the IDevice interface consumer class (Man). The Moq library creates the object with expected IDevice implementation for you.

No comments: