ntroduction
There are several mocking frameworks to be used in testing environments, such as NMock, RhinoMocks, FakeItEasy, and Moq, to isolate units to be tested from the underlying dependencies. Although Moq is a relatively new mocking framework, this framework has been adapted by the developers because it's very easy to use, not following the traditional mock pattern Record/Replay, which is very opaque and unintuitive; it supports full VS Intellisense when creating the mock objects as well as it supports the new features of Microsoft.NET 2.0/3.5/4.0 such as dynamic typing, lambda expressions and LINQ expressions in C#. So, you, as a developer, will have a very low learning curve when using mocking frameworks.
I will explain how to use this amazing mocking framework in this article.
Suppose we need to build a Calculator that provides basic arithmetic operations and a currency conversion operation (in this case, converting a dollar to Chilean pesos according to the actual exchange rate).
Let's define the ICalculator interface (see Listing 1).
Listing 1
Let's suppose that we will consume an external service that provides the actual exchange rate for the USD and CLP. Let's define the IUSD_CLP_ExchangeRateFeed interface (see Listing 2).
Listing 2
Now let's define the Calculator class to realize the ICalculator interface. Let's use Dependency Injection programming techniques to inject an object realizing the IUSD_CLP_ExchangeRateFeed interface using the constructor of the Calculator class. Finally, let's implement each class method (see Listing 3).
Listing 3
Now let's prepare the testing environment for the Calculator component. We're going to use the NUnit testing framework and Moq mocking framework.
To get started with NUnit, you just need to download the framework from http://www.nunit.org/ and install it.
To start with Moq, you just need to download the framework in a zip archive from http://code.google.com/p/moq/ and extract it to a location to reference the Moq.dll assembly from your testing environment.
Then, we create a testing library, add the references to NUnit and Moq frameworks, and add the tester class CalculatorTester to define the test cases.
Moq is a very easy-to-use mocking framework. To define the mock objects, we use generics passing the interface as the type. The behavior of the mock objects is done using basically a set of lambda expressions, making the code more productive and type-safe (see Listing 4).
Listing 4
The final code for the testing cases is shown in Listing 5.
No comments:
Post a Comment