rhino mocks

Understanding Mock and frameworks – Part 4 of N

January 25, 2013 CSharp, Open Source, Unit Testing, Visual Studio , , , , , , , , ,

I am glad that this series has been liked by large audience and even got focus on Channel9 Video and that motivates to continue this series further on.

This series on Mock and frameworks takes you through Rhino Mocks, Moq and NSubstitute frameworks to implement mock and unit testing in your application.  This series of posts is full of examples, code and illustrations to make it easier to follow.  If you have not followed this series through, I would recommend you to read following articles

  1. Understanding Mock and frameworks – Part 1 of N – Understanding the need of TDD, Mock and getting your application Unit Test ready
  2. Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq
    1. Understanding Mock and frameworks – Part 3 of N -  Understanding how to Mock Methods calls and their Output – Rhino Mocks, NSubstitute and Moq

    This part of the series will focus on exception management, and subscribing to events

    Exception Management

     

    Going back to the second post where we defined our Controller and Service interface,  the method GetObject throws an ArgumentNullException when a NULL value is passed to it.  The Exception Management with Mock allows you to change the exception type and hence, ignore the exception peacefully.

    Using Rhino Mocks

    Using the Stub method of Mocked Service, you can override the exception type.  So instead of getting a ArgumentNullException, we will change the exception to InvalidDataException.  But do not forget to add a ExceptedException attribute to the method (line 2 in example below) that ensures a peaceful exit.

    1. [TestMethod]
    2. [ExpectedException(typeof(InvalidDataException))]
    3. public void T05_TestExceptions()
    4. {
    5.     var service = MockRepository.GenerateMock<IService>();
    6.     // we are expecting that service will throw NULL exception, when null is passed
    7.     service.Stub(x => x.GetObject(null)).Throw(new InvalidDataException());
    8.     
    9.     Assert.IsNull(service.GetObject(null)); // throws an exception
    10. }

    Using NSubstitute

    NSubstitute does not expose a separate /special function like Throw. It treats exceptions as a return value of the test method. So u

    1. [TestMethod]
    2. [ExpectedException(typeof(InvalidDataException))]
    3. public void T05_TestExceptions()
    4. {
    5.     var service = Substitute.For<IService>();
    6.     // we are expecting that service will throw NULL exception, when null is passed
    7.     service.GetObject(null).Returns(args => { throw new InvalidDataException(); });
    8.     
    9.     Assert.IsNull(service.GetObject(null)); // throws an exception
    10. }

    Using Moq

    Moq exposes Throws method just like Rhino Mocks

    1. [TestMethod]
    2. [ExpectedException(typeof(InvalidDataException))]
    3. public void T05_TestExceptions()
    4. {
    5.     var service = new Mock<IService>();
    6.     // we are expecting that service will throw NULL exception, when null is passed
    7.     service.Setup(x => x.GetObject(null)).Throws(new InvalidDataException());
    8.     
    9.     Assert.IsNull(service.Object.GetObject(null)); // throws an exception
    10. }

    Event Subscriptions

    The next topic of interest in this series is managing Event Subscriptions with Mock frameworks. So the target here is to check if an event was called when some methods were called on the mocked object

    Using Rhino Mocks

    The code here is little complex compared to all previous examples.  So we are adding a ServiceObject to the controller which raises an event. Unlike real time examples, this event is hooked to the DataChanged method of the service. This means the controller will raise an event and a service method will be called dynamically.

    1. [TestMethod]
    2. public void T06_TestSubscribingEvents()
    3. {
    4.     var service = MockRepository.GenerateMock<IService>();
    5.     var controller = new Controller(service);
    6.  
    7.     controller.CEvent += service.DataChanged;
    8.     ServiceObject input =new ServiceObject("n1", Guid.NewGuid());
    9.     controller.Add(input);
    10.  
    11.     service.AssertWasCalled(x => x.DataChanged(Arg<Controller>.Is.Equal(controller),
    12.         Arg<ChangedEventArgs>.Matches(m=> m.Action == Action.Add &&
    13.                                               m.Data == input)));
    14. }

    Let’s go into detail of the AssertWasCalled statement – it takes a method handler in the lambda expression. Some of the other methods of interest are Arg<T> Is.Equal and Matches. The method Arg<T> creates a fake argument object of a particular type. Is.Equal() method assigns a value to it and Matches method adds like a filter on the values of input parameters to the original ‘DataChanged’ method.

    Using NSubstitute

    NSubstitute has a different set of methods for event subscription.  The output of Received() method exposes all valid method calls available, Arg.Is<T>() creates fake object for mocked service.

    1. [TestMethod]
    2. public void T06_TestSubscribingEvents()
    3. {
    4.     var service = Substitute.For<IService>();
    5.     var controller = new Controller(service);
    6.  
    7.     controller.CEvent += service.DataChanged;
    8.     ServiceObject input = new ServiceObject("n1", Guid.NewGuid());
    9.     controller.Add(input);
    10.  
    11.     service.Received().DataChanged(controller,
    12.       Arg.Is<ChangedEventArgs>(m => m.Action == Action.Add && m.Data == input));
    13. }

    Using Moq

    Apart from having different names of methods from NSubstitute, Moq does exactly the same as other two frameworks

    1. public void T06_TestSubscribingEvents()
    2. {
    3.     var service = new Mock<IService>();
    4.     var controller = new Controller(service.Object);
    5.  
    6.     controller.CEvent += service.Object.DataChanged;
    7.     ServiceObject input = new ServiceObject("n1", Guid.NewGuid());
    8.     controller.Add(input);
    9.  
    10.     service.Verify(x => x.DataChanged(controller,
    11.         It.Is<ChangedEventArgs>(m => m.Action == Action.Add && m.Data == input)));
    12. }

    The Code for Download

    Understanding RhinoMocks, NSubstitute, Moq by Punit Ganshani

    So that concludes how to use Rhino Mocks, NSubstitute and Moq for Exception Handling and Event Subscriptions.  Should you have any questions, feel free to comment on this post.

    Understanding Mock and frameworks – Part 3 of N

    January 22, 2013 CSharp, Open Source, Unit Testing, Visual Studio , , , , , , , ,

    This series on Mock frameworks takes you through Rhino Mocks, Moq and NSubstitute frameworks to implement mock and unit testing in your application.  This series of posts is full of examples, code and illustrations to make it easier to follow.  If you have not followed this series through, I would recommend you reading following articles

    1. Understanding Mock and frameworks – Part 1 of N – Understanding the need of TDD, Mock and getting your application Unit Test ready
    2. Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq

    In Part 1, we understood how to refactor our application so that it can be Unit tested with Mock frameworks and in Part 2, we understood 3 stages of Mocking – Arrange, Act and Assert with an example.  Now as understood in Part 2 ‘Arrange’ is the stage where implementation in all the three framework differs.  So in this post, we will focus on ‘Arrange’ and explore various types of mocking.

    Mocking Method Calls

    In the examples below, we will mock a method call GetCount of the service so that it returns value 10.  We will clear the controller and then check if GetCount method was actually called.  If this example was called without using Mock frameworks, the outputs would have been different. Please note that in the below examples all the mock methods are applied on the service; however, you can apply them on the controller as well.

    Using Rhino Mocks

    Rhino Mocks uses methods AssertWasCalled and AssertWasNotCalled to check if the ‘actual’ method was invoked.

    1. [TestMethod]
    2. publicvoid T03_TestMethodCall()
    3. {
    4.     var service = MockRepository.GenerateMock<IService>();
    5.     var controller = newController(service); // injection
    6.     service.Stub(x => x.GetCount()).Return(10);
    7.     controller.Clear();
    8.     service.AssertWasNotCalled(x => x.GetCount());
    9.     service.AssertWasCalled(x => x.Clear());
    10. }

    Using NSubstitute

    NSubstitute uses DidNotReceive and Received methods to check if the ‘actual’ methods got a call or not.  There are multiple similar methods available such as DidNotReceiveWithAnyArgs, ClearReceivedCalls, and ReceivedCalls.  Each of these functions can be used to manipulate or check the call stack.

    1. [TestMethod]
    2. publicvoid T03_TestMethodCall()
    3. {
    4.     var service = Substitute.For<IService>();
    5.     var controller = newController(service);
    6.     service.GetCount().Returns(10);
    7.     controller.Clear();
    8.     service.DidNotReceive().GetCount();
    9.     service.Received().Clear();
    10. }

    Using Moq

    Moq standardizes the verification of method calls with a single method Verify. The Verify method has many overloads allowing to even evaluate an expression.

    1. [TestMethod]
    2. publicvoid T03_TestMethodCall()
    3. {
    4.     var service = newMock<IService>();
    5.     var controller = newController(service.Object);
    6.     service.Setup(x => x.GetCount()).Returns(0);
    7.     controller.Clear();
    8.     service.Verify(x => x.GetCount(), Times.Never());
    9.     service.Verify(x => x.Clear());
    10. }

    Mocking Method Calls and their Output

    The next example focuses on a more real time scenario, where we will mock a method that takes input parameters and returns an output parameter.  The service will be mocked and we will test the functionality of our controller.

    So going back to Part 2 of our series, if a NULL input is passed to Add method of the controller it returns back false.  For any non-NULL input, it gives a call to Add method of the service and returns back the value returned by the service.  So we will pass two different types of objects to the controller and return 2 different outputs based on our mock.  When we pass ServiceObject with name ‘m1’ we will mock it to return value ‘false’ while ServiceObject with name ‘m2’ should return value ‘true’

    Using Rhino Mocks

    What’s important to focus at his moment is that we altered the behavior and hence used the method Stub on the mocked service and then later we defined the expected result by the method Returns.

    1. [TestMethod]
    2. publicvoid T04_TestConditions()
    3. {
    4.     var service = MockRepository.GenerateMock<IService>();
    5.     var controller = newController(service); // injection
    6.     ServiceObject oneThatReturnsFalse = newServiceObject(“m1”, Guid.NewGuid());
    7.     ServiceObject oneThatReturnsTrue = newServiceObject(“m2”, Guid.NewGuid());
    8.     service.Stub(x => x.Add(oneThatReturnsFalse)).Return(false);
    9.     service.Stub(x => x.Add(oneThatReturnsTrue)).Return(true);
    10.     Assert.AreEqual(false, controller.Add(oneThatReturnsFalse));
    11.     Assert.AreEqual(true, controller.Add(oneThatReturnsTrue));
    12. }

    Using NSubstitute

    NSubstitute does not require any method like Stub. When you are defining any method on the mocked service object, it automatically assumes that the framework has to alter the behavior of the method.  Just like Rhino Mocks, method Returns defines the expected mocked output of that method.

    1. [TestMethod]
    2. publicvoid T04_TestConditions()
    3. {
    4.     var service = Substitute.For<IService>();
    5.     var controller = newController(service);
    6.     ServiceObject oneThatReturnsFalse = newServiceObject(“m1”, Guid.NewGuid());
    7.     ServiceObject oneThatReturnsTrue = newServiceObject(“m2”, Guid.NewGuid());
    8.     service.Add(oneThatReturnsFalse).Returns(false);
    9.     service.Add(oneThatReturnsTrue).Returns(true);
    10.     Assert.AreEqual(false, controller.Add(oneThatReturnsFalse));
    11.     Assert.AreEqual(true, controller.Add(oneThatReturnsTrue));
    12. }

    Using Moq

    Moq like Rhino Mocks requires a special method call Setup and then followed by another method call to Returns method

    1. [TestMethod]
    2. publicvoid T04_TestConditions()
    3. {
    4.     var service = newMock<IService>();
    5.     var controller = newController(service.Object);
    6.     ServiceObject oneThatReturnsFalse = newServiceObject(“m1”, Guid.NewGuid());
    7.     ServiceObject oneThatReturnsTrue = newServiceObject(“m2”, Guid.NewGuid());
    8.     service.Setup(x => x.Add(oneThatReturnsFalse)).Returns(false);
    9.     service.Setup(x => x.Add(oneThatReturnsTrue)).Returns(true);
    10.     Assert.AreEqual(false, controller.Add(oneThatReturnsFalse));
    11.     Assert.AreEqual(true, controller.Add(oneThatReturnsTrue));
    12. }

    Strict Mock vs Normal Mock

     

    Strict Mock creates brittle tests.   A strict mock is a mock that will throw an exception if you try to use any method that has not explicitly been set up to be used.  A dynamic (or loose, normal) mock will not throw an exception if you try to use a method that is not set up, it will simply return a default value from the method and keep going.  The concept can be applied to any mocking framework that supports these 2 types of mocking.

    Let’s see an example with Rhino Mocks.  We will alter our controller class to add a method Find that invokes two methods of our IService interface

    1. publicpartialclassController
    2. {
    3.     publicServiceObject Find(string name)
    4.     {
    5.         if (string.IsNullOrEmpty(name))
    6.             thrownewArgumentNullException(name);
    7.         if (_service.GetCount() > 0)
    8.         {
    9.             /* Can have more business logic here */
    10.             return _service.GetObject(name);
    11.         }
    12.         else
    13.         {
    14.             returnnull;
    15.         }
    16.     }
    17. }

    Now with a Strict Mock on the method GetObject and no mock on method GetCount, we should expect an exception to be thrown.  However, when using a dynamic/loose mock, GetCount will return its default value which is Zero (0 ) and hence Find Method will return NULL

    1. [TestMethod]
    2. publicvoid T10_TestStrictMock()
    3. {
    4.     // data
    5.     string name = “PunitG”;
    6.     ServiceObject output = newServiceObject(name, Guid.NewGuid());
    7.     // arrange
    8.     var service = MockRepository.GenerateMock<IService>();
    9.     var controller = newController(service);
    10.     var strictService = MockRepository.GenerateStrictMock<IService>();
    11.     var controllerForStrictMock = newController(strictService);
    12.     // act
    13.     service.Stub(x => x.GetObject(name)).Return(output);
    14.     // assert
    15.     Assert.AreEqual(null, controller.Find(name));
    16.     Assert.AreEqual(output, controllerForStrictMock.Find(name)); // exception expected
    17. }

    When you execute this Test, the first assert will pass and the second assert will throw an exception.  Overall the test will fail.

    The Code for Download

    Understanding RhinoMocks, NSubstitute, Moq by Punit Ganshani

    Hope this helps. In the next post, we will explore how to mock Exceptions and Events

    Understanding RhinoMocks, NSubstitute and Moq

    January 20, 2013 CSharp, Open Source, Visual Studio , , , , ,

    For those who are following me on Codetails, would know that I am actively blogging (since Nov 2012) on Codetails on all technology stuff.  One of the series of articles I wrote on Codetails that got great applause from the technical community is on Mocking Frameworks with .NET Here are the links that describe the technical details

    1. Understanding Mock and frameworks – Part 1 of N – Understanding the need of TDD, Mock and getting your application Unit Test ready
    2. Understanding Mock and frameworks – Part 2 of N – Understanding Mock Stages & Frameworks – Rhino Mocks, NSubstitute and Moq
    3. Understanding Mock and frameworks – Part 3 of N –  Understanding how to Mock Methods calls and their Output – Rhino Mocks, NSubstitute and Moq
    4. Understanding Mock and frameworks – Part 4 of N –  Understanding how to Mock Exceptions and Event Subscriptions  – Rhino Mocks, NSubstitute and Moq

    And here is my proud moment – featured on Microsoft Channel9

    Linkhttp://channel9.msdn.com/Shows/This+Week+On+Channel+9/TWC9-January-18-2013

    Understanding Mock and frameworks – Part 2 of N

    January 10, 2013 CSharp, Open Source, Unit Testing, Visual Studio , , , , , , , , ,

    Continuing on where we left in the previous post – Understanding Mock and frameworks Part 1 – this post will take a very simple example and illustrate how to implement Mock frameworks.  I was mailed by one of our readers asking if I could define TDD – Test Driven Development in my words.

    Test driven development is a methodology that states that test cases should be driving the design decisions and development.  This also that TDD advocates knowing the expected behaviour of our application (or a part of it), before we write the code.  It also enforces incremental design and allows us to write just enough code to pass our test. That means, no redundant code (YAGNI – You ain’t gonna need it) ships with our product, and our code is fairly simple (KISS – Keep it simple, stupid!) to understand. Sounds cool, isn’t it?

    So you start writing tests first, design your application gradually and then start writing the implementation so that each test passes.  I prefer TDD over Test-After-Development (TAD) where you first design your application and write code.  Once your code is complete (or partially complete), you write the required test cases. Theoretically, a TAD system would appear to produce as high-quality product as TDD would.  But to my opinion, TAD involves taking design decisions up front – right from the start rather than taking incremental baby steps.  This also means that when time to delivery is short and critical, there are chances of not having a 100% code coverage by TAD approach. Also, a developer can fall victim to his own ego that “I don’t bad write code that needs to be tested”

    That’s the way I see Test Driven Development (TDD) and Test-After-Development (TAD). So let’s get back to our topic of interest – an example to get started with Unit Testing with Mocks.

    The service (or data source) interface

    Assume that you are building an application that interfaces with just one service.  We have refactored our application to follow SOLID principles such as SRP, ISP, DIP and DI.  The service implements an interface IService.   This service interface could be interface of your internal service, or an external service whose behaviour and availability can not be controlled by you.

    At this moment, we are not really interested in the implementation of IService and we will restrict our scope to the interface and the consumer (i.e. our application).

    public interface IService
        {
            string ServiceName { get; set; }
    
            bool Add(ServiceObject input);
            bool Remove(ServiceObject input);
            void Clear();
            int GetCount();
            ServiceObject GetObject(string name);
    
            void DataChanged(object sender, ChangedEventArgs args);
        }
    
        public class ServiceObject
        {
            public string Name { get; set; }
            public Guid Ref { get; set; }
            public DateTime Created { get; set; }
    
            public ServiceObject(string name, Guid reference)
            {
                Name = name;
                Ref = reference;
                Created = DateTime.Now;
            }
        }
    
        public enum Action
        {
            Add,
            Remove,
            Clear
        }

    The Controller (or our application)

     

    The consuming class (let’s call it Controller) isolates the dependency on the implementation of service object and ensures that the consuming class injects the appropriate service object.

    public class Controller
        {
            private IService _service;       
    
            public Controller(IService service)
            {
                _service = service;
            }
        }

    In reality, the Controller class could be just a facade or can contain business logic, or data manipulation and a lot of other complex logic.  For this example, it is kept simple and restricted to only service calls.   So our controller class looks like,

    1. public class Controller
    2. {
    3.     private IService _service;
    4.  
    5.     /// <summary>
    6.     /// To demonstrate events in Mock
    7.     /// </summary>
    8.     public event EventHandler<ChangedEventArgs> CEvent;
    9.  
    10.     public Controller(IService service)
    11.     {
    12.         _service = service;
    13.     }    
    14.     
    15.     private void RaiseEvent(Action action,
    16.                     ServiceObject input)
    17.     {
    18.         /* Can have more business logic here */
    19.         if (CEvent != null)
    20.             CEvent(this, new ChangedEventArgs(action, input));
    21.     }
    22.  
    23.     /// <summary>
    24.     /// To demonstrate methods with parameters and return value
    25.     /// in Mock
    26.     /// </summary>
    27.     public bool Add(ServiceObject input)
    28.     {
    29.         if (input == null)
    30.             return false;
    31.  
    32.         /* Can have more business logic here */
    33.  
    34.         _service.Add(input);
    35.         RaiseEvent(Action.Add, input);
    36.  
    37.         return true;
    38.     }
    39.  
    40.     /// <summary>
    41.     /// To demonstrate simple method calls in Mock
    42.     /// </summary>
    43.     public void Clear()
    44.     {
    45.         _service.Clear();
    46.     }
    47. }

     

    So to create an object of our controller, we need to pass an instance of a class that implements IService. As said earlier, we will not implement the interface IService to ensure that we do not have a functional service (to create a scenario of an unavailable service) for testing.  So let’s get started with our Mocking the interface IService.

     

    Mocking – Step Arrange

    All our tests will follow three step process

    • Arrange – This step involves creating a service/interface mock (using a Mock framework) and creating all required objects for that service/interface.  This step also includes faking the object behaviour.
    • Act – This step involves calling a method of the service, or performing any business functionality
    • Assert – This step usually asserts whether the expected result is obtained from the previous step (‘Act’) or not

    Step Arrange: With Rhino Mocks

    Rhino Mock framework maintains a repository of Mocks.   The MockRepository can be seen to follow a Factory design pattern to generate Mocks using Generics, object(s ) of Type, or stubs.  One of the ways to generate a Mock is,

    1. // Arrange
    2. var service = MockRepository.GenerateMock<IService>();
    3. var serviceStub = MockRepository.GenerateStub<IService>();

    There is a minor difference between a Mock and a Stub. A discussion on StackOverflow explains it very appropriately or Martin Fowler has explained it brilliantly in his post on Mocks Aren’t Stubs. To keep it short and simple,

    Mock objects are used to define expectations i.e: In this scenario I expect method A() to be called with such and such parameters. Mocks record and verify such expectations. Stubs, on the other hand have a different purpose: they do not record or verify expectations, but rather allow us to “replace” the behaviour, state of the “fake”object in order to utilize a test scenario.

    If you want to verify the behaviour of the code under test, you will use a mock with the appropriate expectation, and verify that. If you want just to pass a value that may need to act in a certain way, but isn’t the focus of this test, you will use a stub.

    Once the object has been created, we need to mock the service behaviour on this fake service object.  Let’s see how to fake a property

    1. // Arrange
    2. var service = MockRepository.GenerateMock<IService>();            
    3. service.Stub(x => x.ServiceName).Return("DataService");

    Similarly, we can mock methods.  We will see mocking different types in detail later.

     

    Step Arrange: With NSubstitute

    NSubstitute makes it simpler to read, interpret and implement.

    1. // Arrange
    2. var service = Substitute.For<IService>();

    Mocking property in NSubstitute is a lot easier to remember

    1. // Arrange
    2. var service = Substitute.For<IService>();            
    3. service.ServiceName.Returns("DataService");

    Step Arrange: With Moq

    Moq like Rhino Mocks also has MockRepository.  You can choose a mock to be a part of MockRepository or to let it hang individually.  Both the methods are shown as below.

    1.           // Arrange
    2.             var service = newMock<IService>();
    3.  
    4.           MockRepository repository = new MockRepository(MockBehavior.Default);
    5.           var serviceInRepository = repository.Create<IService>();

    Mocking property is somewhat similar to Rhino Mocks

    1.           // Arrange
    2.             var service = newMock<IService>();
    3.           service.Setup(x => x.ServiceName).Returns("DataService");

    Rhino Mocks and Moq both have two different types of behaviours’ – Strict and Loose (default).  We will look into what each of them means in the next article.

    Mocking – Step Act, Assert

    Once we have the fake service and have defined the expected behaviour, we can implement the next step.  This step involves calling a method of the service, or performing any business functionality. So here we can call a method of service, or use its output to do some work.  So our examples will vary from setting something in mocked service object to calling its methods.

    Step Act and Assert: With Rhino Mocks and NSubstitute

    As the output of the first step, both Rhino Mock and NSubstitute give you directly an object of IService (named, service).  So you can directly use this object as a substitute of the actual service.  The object service is a fake object whose ServiceName is expected to be "DataService".  Just to remind that in actual, neither the implementation of the service nor a real object of the service exists.  We are dealing with fake objects through all our examples

    1. // Act
    2. var actual = service.ServiceName;
    3.  
    4. // Assert
    5. Assert.AreEqual("DataService", actual);

    This test on execution will give a PASS

    Step Act and Assert: With Moq

    Moq unlike the other two frameworks does not directly provide you a fake service object.  It provides you the fake service object in one of its properties called ‘Object’.  Everything else remains the same

    1. // Act
    2. var actual = service.Object.ServiceName;
    3.  
    4. // Assert
    5. Assert.AreEqual("DataService", actual);

    If you put together the code, it forms our first Unit Test w/Mock frameworks.

    The Code for Download

    Understanding RhinoMocks, NSubstitute, Moq by Punit Ganshani

    In the next article, we will look into creating Mocks for methods using these frameworks.

    Follow on Feedly