Tuesday, November 9, 2010

UnitTesting using Moq

I am a firm believer of writing unit test before you check in any code. Writing unit test and making sure that your code works as expected gives a lot more confidence in your code.

One of the libraries that I use which makes my unit testing code easier to write is Mocking Framework like Moq. Moq is a cool library I love to use. The api that MOQ has are so easy to find out and understand what they actually do. I would recommend this framework to anyone who is starting doing Unit Tests.

Some of the important things while writing code that you have to always keep in mind are:

1) Open-Closed principle.. i.e open for extension closed for modification.
2) Single Point of responsibility.
3) Program to an interface and not to concrete classes.
4) Prefer composition over inheritance. etc

In this sample example I want to test the LibraryService Class which takes in 1 dependency - IDataService. The dependency is passed in through constructor injection. This is one was to inject the dependency, and the code is not tightly couple to a particular instance of the DataService. You can implement IDataService which gets the books from the DataBase or XmlFile or any other datasource.

Highlighted text shows the dependency. The simple task here to unit test the GetBook function. Using MOQ its so easy to test this function.


Here I am mocking an Instance of IDataService which I is the passed to the Library Service. Then I am setting the expectation by using the SetUp methof of MOQ. See the cool use of Lambda expression to find out the Method which we are setting expectation on.

What this does is when the GetBook function is called it will make a call to the GetBooks function and will return the books object (i.e the one that we set in the expectation). The actual call wont happen. This is really cool because then you can test each piece independently.

One more important thing is the call to the Verify function on the moq. This will verify all the expectations that were set on the Mock object, in this case if the GetBooks function was call with the right parameters and was called once or not.

Moq is very powerful is very easy to use. It doesn't have a huge learning curve!

I Hope this helps someone :)

Code: Download!

-Yash