Decaying Code

Where code comes to die

About the author

Maxime Rouiller is a passionate .NET technology specialist, working for 7 years in large software development, advocating Agile and TDD. Aware of the latest technological trends, he intervenes as a specialist in the .NET Montréal usergroup and acts regularly as a speaker for Web Form programmers on the MVC platform.

View Maxime Rouiller's profile on LinkedIn

Month List

CodeCamp Montreal 2009 - Unit testing with Moq

I'm happy to announce you that I've been selected to present a session at the Montreal CodeCamp.

My session is going to be focussed on Moq and unit testing. Since simply looking at a framework can be done simply, I'll be going over the framework and many "how-to". I'll also try to fit a few interesting demo with some "refactoring for unit test". Of course, this will all be centered around "best practices" since it's the theme of this year.

See you all there!


Categories: mock | moq | presentation | unit test
Permalink | Comments (0) | Post RSSRSS comment feed

"Utilisations des mocks avec Moq" - Using mocks with Moq

For those who attended my presentation at the Montreal .NET User Group, here is a list of links that I mentioned inside my presentation:


Categories: mock | moq | presentation
Permalink | Comments (0) | Post RSSRSS comment feed

Part 3 - Advanced mocking functionalities of Moq

See also: Part 1 - Part 2

When you have some simple scenario like "when the method "GetTax" is called, return 5$" it's a simple scenario that a lot of mockers will see. However, there is some rarer scenario that people will wonder how to do it.

One of those scenario is with event handlers. The scenario would be like "if a Product is added to a ShoppingCart, a ProductAdded event should be fired".

Let's start with the basic class bellow which implement our scenario:

namespace MoqSamples
        {
        public interface IProduct
        {
        bool IsValid { get; }
        }

        public class ProductEventArgs : EventArgs
        {
        public ProductEventArgs(IProduct product)
        {
        Product = product;
        }

        public IProduct Product { get; private set; }
        }

        public class ShoppingCart
        {
        private readonly List<IProduct> Products = new List<IProduct>();
        public event EventHandler<ProductEventArgs> ProductAdded = delegate { };

        public void Add(IProduct product)
        {
        if (product.IsValid)
        {
        Products.Add(product);
        ProductAdded(this, new ProductEventArgs(product));
        }
        }
        }
        }

Event Handlers

What we want to test here, is every time we add a valid product an event ProductAdded should be fired.

I have played with Moq a bit trying to get it to work with ShoppingCart. As I tried to mock the event, I tried to create mocks and use the instructions on Moq site but wasn't able to make it happen. If I tried to mock the class itself it wouldn't allow me to do expectations even if I extracted an interface out of it. If I mock the interface, I lose the logic inside my class. I was thinking about creating a mocked event handlers and see if it ever get called but... you need a mock to create a mocked event handler. With this, we'll have to wait for Moq 3.0 (which is in beta at the moment of writing this article). Here is the test I came up with that didn't work :

[Test]
        public void Adding_A_Valid_Product_Fire_Event()
        {
        // Setup our product so that it always returns true on a IsValid verification
        Mock<IProduct> product = new Mock<IProduct>();
        product.Expect(currentProduct => currentProduct.IsValid).Returns(true);

        // setup an event argument for our event
        ProductEventArgs productEventArgs = new ProductEventArgs(product.Object);

        // setup a mocked shopping cart to create our mocked event handler and a true shopping cart to test
        Mock<ShoppingCart> mockedShoppingCart = new Mock<ShoppingCart>();

        //creating the event a mocked event
        MockedEvent<ProductEventArgs> mockedEvent = mockedShoppingCart.CreateEventHandler<ProductEventArgs>();
        mockedShoppingCart.Object.ProductAdded += mockedEvent;
        mockedShoppingCart.Expect(shopping => shopping.Add(product.Object)).Raises(mockedEvent, productEventArgs).Verifiable();

        //making the test
        IShoppingCart myShoppingCart = mockedShoppingCart.Object;
        myShoppingCart.Add(product.Object);

        mockedShoppingCart.Verify();
        }

And here is my simple fix to test this:

[Test]
        public void Adding_A_Valid_Product_Fire_Event()
        {
        // Setup our product so that it always returns true on a IsValid verification
        Mock<IProduct> product = new Mock<IProduct>();
        product.Expect(currentProduct => currentProduct.IsValid).Returns(true);

        // setup an event argument for our event
        ProductEventArgs productEventArgs = new ProductEventArgs(product.Object);

        // creating our objects and events
        ShoppingCart myShoppingCart = new ShoppingCart();
        bool isCalled = false;
        myShoppingCart.ProductAdded += (sender, e) => isCalled = true;

        // Testing the Add method if it fire the event
        myShoppingCart.Add(product.Object);

        // make sure the event was called
        Assert.AreEqual(isCalled, true);
        }

Way more small and more efficient with the mocking. Sometimes, it's better not to try to bend the framework and find the shortest solution that works.

Moq Factories

Moq have factories to help centralize the mocking configuration. The only two configuration available is CallBase and DefaultValue. Every mock created with the factories will allow you to reuse the configuration and reduce the amount of line for setting up the mock.

Here's a sample for the factory initialization:

[Test]
        public void Moq_Test_With_Factories()
        {
        // Initialize factories with default behaviours
        MockFactory mockFactory = new MockFactory(MockBehavior.Default);

        // Setup parameters for mocking
        mockFactory.CallBase = true;
        mockFactory.DefaultValue = DefaultValue.Mock;

        // create mocks with the factory
        Mock<IProduct> product = mockFactory.Create<IProduct>();
        }

This is of course really easy but... what about the parameters?

CallBase

CallBase is defined as "Invoke base class implementation if no expectation overrides the member. This is called "Partial Mock". It allows to mock certain part of a class without having to mock everything.

DefaultValue

There is 2 possible values here. One of them is "Empty" which return default value of the class. The one used in the example is "Mock" which allows "automocking". If a property is mockable, a mock is automatically returned.

Constructor

The constructor of the MockFactory needs a MockBehaviour parameter. 3 values are possible, Default, Loose and Strict.

Strict mock makes mocked object throw an exception for every call to a mocked object that doesn't have an expectation. Loose (which is also Default) will always return default values or empty arrays or null.

By using the factory properly, it's possible to set one style of mocking and reuse theses settings without having to rewrite 1 or 2 more lines per mock.


Categories: c# | mock | moq | unit test
Permalink | Comments (2) | Post RSSRSS comment feed

Why should I use mocking objects in my Unit Test?

If we cut out any "fanboy" or favouritism toward certain framework and that we try to keep it in a one liner... I would say: "To simulate behaviours of objects that are impractical or impossible to incorporate inside a unit test".

The Wikipedia's article about Mock Object mention some reason an object should be mocked.

The object...

Supplies Non-Deterministic Results

By "non-deterministic" we mean everything from time, currency rate, shipping rate, etc. Any value that could be changing because of a specific implementation such as algorithm should be mocked. Mocked object allows you to return predetermined value that are independent of the algorithm/time/etc.

This allows to more easily test the state of the System Under Test (SUT) after running some methods.

Has States that are difficult to create or reproduce

The example given by Wikipedia is "network error". It's difficult to reproduce this kind of situation on every developers station. Other situation might include security, location of the test on disk, network availability (not just errors). If some objects that the SUT is using require any of those, the tests WILL fail somewhere and somehow. If it's not on a developer's machine, it's going to be on the build machine.

Mocking those objects and giving them proper behaviour will remove any required "settings" that are necessary to run a Unit Test.

Is Slow

Databases, network, file access (up to a point) are all slow. If your SUT is an ObjectService that is using a Repository and you are hitting directly on the databases, it is bound to be slow. Of course the database can cope with it. But as you had more tests, the unit will soon take HOURS to run. With a small in-memory database will save the day and run those tests in less than a few minutes.

A mocked repository might just keep a collection of saved object so that when a "Get" method is called, it's readily available in this collection. This kind of mock is called a "fake" in the world of Mocking. It implements more complex behaviour but allows for easy initialization and more timely responses.

Does not yet exist or may change behaviour

If the only thing that is currently available within your system boundaries are contracts (Interfaces in C#), it's more easy to mock the interface that the SUT is requiring and go with this temporarily while the component is being developed. This allow testing and coding at the same time.

Conclusion

Mocking is an excellent tool to test a specific object under controlled conditions. Of course, those conditions are bound to change and tests are going to be maintained. Why I particularly like is when I use a mocking framework, I don't need to create 1000+ objects (exaggerating here) with some specific behaviours or create "too intelligent" mock that will have to be maintained. I dynamically declare a mock with my favourite mocking framework with the expected call and the expected returns and I go through with that.

What normally happens is I have considerably less mocking objects inside my Unit Tests and the only objects that are left standing are some in-memory database objects with simple implementation that would be to hard to define with a mocking framework.


Categories: architecture | mock | opinion
Permalink | Comments (0) | Post RSSRSS comment feed

Part 2 - Basic of mocking with Moq

See also:  Part 1 - Part 3

As every mocking framework, except TypeMock which can perform differently, every mocked class can't be sealed and methods that need to be mocked need to be public. If  the class is not inheriting from an interface, the method that are being mocked need to be virtual.

Once this is cleared... let's show a simple example of a Product having it's price calculated with a Tax Calculator.

Here's what we are starting with:

public class Product
{
    public int ID { get; set; }
    public String Name { get; set; }
    public decimal RawPrice { get; set; }
    public decimal GetPriceWithTax(ITaxCalculator calculator)
    {
        return calculator.GetTax(RawPrice) + RawPrice;
    }
}

public interface ITaxCalculator
{
  decimal GetTax(decimal rawPrice);
}

The method we want to test here is Product.GetPriceWithTax(ITaxCalculator). At the same time, we don't want to instantiate a real tax calculator which gets it's data from a configuration or a database. Unit tests should never depend upon your application's configuration or a database. By "application's configuration", I mean "App.config" or "web.config" which are often changed during the life of an application and might inadvertently fail your tests.

So, we are going to simply mock our tax calculator like this:

//Initialize our product
        Product myProduct = new Product {ID = 1, Name = "Simple Product", RawPrice = 25.0M};

        //Create a mock with Moq
        Mock<ITaxCalculator> fakeTaxCalculator = new Mock<ITaxCalculator>();

        // make sure to return 5$ of tax for a 25$ product
        fakeTaxCalculator.Expect(tax => tax.GetTax(25.0M)).Returns(5.0M);

Now It all depends on what you want to  test. Depending if you are a "State" (Classic) or "Behaviour verification" (Mockist), you will want to test different things. If you don't know the difference, don't bother now but you might want to look at this article by Martin Fowler.

So if we want to make sure that "GetTax" from our interface was called:

// Retrived the calculated tax
        decimal calculatedTax = myProduct.GetPriceWithTax(fakeTaxCalculator.Object);

        // Verify that the "GetTax" method was called from  the interface
        fakeTaxCalculator.Verify(tax => tax.GetTax(25.0M));

If you want to make sure that the calculated price equal your product price with your tax added (which confirm that the taxes were calculated):

// Retrived the calculated tax
        decimal calculatedTax = myProduct.GetPriceWithTax(fakeTaxCalculator.Object);

        // Make sure that the taxes were calculated
        Assert.AreEqual(calculatedTax, 30.0M);

What's the difference? The first example verify the behaviour by making sure that "GetTax" was called. It doesn't care about the value returned. It could return 100$ and it would care. All that mattered in this example was that GetTax was called. Once this is done, we can assume that the expected behaviour was confirmed.

The second example is a state verification. We throw 25$ inside the tax calculator and we expect the tax calculator to return 5$ for a total price of 30$. It wouldn't call GetTax and it wouldn't care. As long as the proper value is returned, it's valid.

Some people will argue that behaviour is better than state (or vice versa). Personally, I'm a fan of both. A good example is that I might want to verify that an invalid invoice will not be persisted to the database and a behaviour verification approach is perfect for this case. But if I'm verifying (like in this case) that the tax were properly calculated, state behaviour is more often than not quicker and more easier to understand.

Nothing prevent your from doing both and making sure that everything works. I'm still not a full fledged TDD developer but I'm trying as much as possible to make tests for my classes as often as possible.

If you found this article helpful, please leave a comment! They will be mostly helpful for my presentation on February 25th 2009 at www.dotnetmontreal.com.


Categories: c# | code snippet | mock | moq | tdd
Permalink | Comments (0) | Post RSSRSS comment feed

Part 1 - Introduction to Moq

See also:  Part 2 - Part 3

This is the first post of a serie on mocking with Moq. I'll be giving a conference a .NET Montreal Community on February 25th and I though there it would be good reference to anyone attending the @Lunch event.

What is Moq?

Moq is a mocking framework like RhynoMock and TypeMock jointly developed by Clarius, Manas and InSTEDD. It heavily use Lambda to create expectations and returning results. It's been highly criticized as not making any distinctions between Mocks and Stubs.

What is import to remember, is that unless you are philosophically attached to your testing style... most developer don't make any different between them and rather do behaviour testing.

Moq easily allows you to change it's behaviour from "Strict" to "Loose" (Loose being the default). Strict behaviour won't allow any calls on the mocked object unless it's been previously marked as expected. Loose will allow all calls and return a default value for it.

There is a lot off more advanced behaviours that can be configured and used.

Why another mocking framework?

Daniel Cazzulino (A.k.a Kzu) blogged a lot about Moq and even compared why he helped in creating Moq. Moq was created to ease the learning curve of learning a mocking framework while blurring the distinctions between mocks and stubs.

Moq allow you to quickly get into mocking (a good thing) while allowing more complex scenarios by more purist mockists. It's the perfect mocking framework if you have never touched a mocking framework and is your first experience.

Where do I download it?

You can download Moq directly here. At the moment of writing this post, Moq was at version 2.6.1014 and Moq 3.0 was available as a beta.

How to install it?

Once Moq is downloaded and extracted from it's zip file, you can easily add the single DLL (Moq.dll) inside your project install it inside the GAC if you are going to use it on many projects.

Stay up to date

After this brief introduction, I'll show more advanced feature of Moq with code sample on how to use them and why to use them.


Categories: c# | mock | moq | tdd
Permalink | Comments (0) | Post RSSRSS comment feed