How to isolate layers and other library using Moles in Unit Testing?

[tweetmeme source=”mradwan06” only_single=false http://www.URL.com]
Moles is one of the Mocking framework for isolation dependencies and other layer’s classes, I used to work with Moq framework and it was very good, but with Mole you can do very good things I don’t know if we can make it with Moq?  like you can isolate your code from .NET Framework code for example how you will isolate DateTime.Now to return specific value that you want?  Remember that you don’t have access definition to the .NET Framework Classes, but with Moles you can do that.

I create a solution from multiple projects so we can investigate Moles, the solution structure as the following:

 

Projects

Project

You will add reference in the Test project to the DB project

Right click on the DB ref and choose Add Mole Assembly

Add Reference

Moles

Start using it as the following

DB Class

[sourcecode language=”csharp”]
using Common;
namespace DB
{
public class DataBase:IDataBase
{
public bool Save(IEmployee e)
{
return true;
}
}
}
[/sourcecode]

Employee Class

[sourcecode language=”csharp”]
using System;
using Common;

namespace DB
{
public class Employee:IEmployee
{
public int Id { get; set; }

public string Name { get; set; }

public DateTime BirthDate { get; set; }
}
}
[/sourcecode]

The Method under the Test

[sourcecode language=”csharp”]
using System;
using Common;
using DB;

namespace TryMole
{
public class MyClas
{
public IDataBase DataBase { get; set; }

public void SaveEmployee(IEmployee e)
{
if (e == null)
throw new ArgumentNullException();
if (e.Id <= 0)
throw new ArgumentException();
if (e.Id > 5000)
throw new ArgumentException();
DataBase.Save(e);
}
}
}
[/sourcecode]

Test Method

[sourcecode language=”csharp”]
[TestMethod()]
public void SaveEmployeeTest()
{
MyClas target = new MyClas(); // TODO: Initialize to an appropriate value
var database = new SIDataBase();
database.SaveIEmployee = (IEmployee emp) => true;
target.DataBase = database;
IEmployee e = new Employee { Id = 5 };
target.SaveEmployee(e);
}
[/sourcecode]

I included also a project that isolate .NET Framework DateTime to return 1/1/2000 Y2K Bug

To download the project and Y2K project click the following link

download

Share This: