This is a mirror of official site: http://jasper-net.blogspot.com/

Mocking in .NET with Moq

| Monday, November 15, 2010
There are several mocking frameworks to be use 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.

In this article, I will explain how to use this amazing mocking framework.

Let's suppose we need to build a Calculator which provides the 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).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CalculatorPkg
{
   public interface ICalculator
   {
       int Add(int param1, int param2);
       int Subtract(int param1, int param2);
       int Multipy(int param1, int param2);
       int Divide(int param1, int param2);
       int ConvertUSDtoCLP(int unit);
   }
}

Listing 1

Let's suppose that we're going to consume an external service which provides the actual exchange rate for the USD and CLP. Let's define the IUSD_CLP_ExchangeRateFeed interface (see Listing 2).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MoneyExchangeRatePkg
{
   public interface IUSD_CLP_ExchangeRateFeed
   {
       int GetActualUSDValue();
   }
}

Listing 2

Read more: C# Corner

Posted via email from .NET Info

0 comments: