Tuesday, 17 September 2013

Unit testing levels of classes with Nunit and Nmock

Unit testing levels of classes with Nunit and Nmock

I have a levels of classes and interfaces namely Level1, Level2 and
Level3. Class Level1 depends on class Level2 and class Level2 depends on
class Level3.
Here is the code for that design:
public interface ILevel1
{
string GetData();
}
public class Level1 : ILevel1
{
ILevel2 level2;
public Level1(ILevel2 level2)
{
this.level2 = level2;
}
public string GetData()
{
// some more process on data.
var data = level2.GetDataAndProc();
data = data + ",Proc at Level1";
return data;
}
}
public interface ILevel2
{
string GetDataAndProc();
}
public class Level2 : ILevel2
{
ILevel3 level3;
public Level2(ILevel3 level3)
{
this.level3=level3;
}
public string GetDataAndProc()
{
var data=level3.GetDataFromDB();
// processing on the data from db.
data=data+ " Processed at level2";
return data;
}
}
public interface ILevel3
{
string GetDataFromDB();
}
public class Level3 : ILevel3
{
public string GetDataFromDB()
{
// Functionalities to get data from db.
return "DB Data";
}
}
Now, i can unit test class Level1 in isolation mocking Level2 interface
and unit test class Level2 in isolation mocking Level3 interface. I am
using Nunit as testing framework and NMock as mocking framework.
So far so good.
But, can i unit test First two levels of code only mocking Level3
interface without mocking Level2? I mean i want to unit test class Level1
without mocking Level2 but mocking Level3. I wanted to do this because
Level3 class gets data from DB and i want to mock only this DB layer so
that my whole project works just with mock db not with real db.

No comments:

Post a Comment