简体   繁体   English

Nunit和Nmock的类的单元测试级别

[英]Unit testing levels of classes with Nunit and Nmock

I have levels of classes and interfaces, namely Level1 , Level2 and Level3 . 我有一些类和接口,分别是Level1Level2Level3
Class Level1 depends on class Level2 and class Level2 depends on class Level3 . Level1类取决于Level2类, Level2取决于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. 现在,我可以在隔离模拟Level2接口中进行单元测试类Level1 ,并在隔离模拟Level3接口中进行单元测试类Level2 I am using Nunit as testing framework and NMock as mocking framework. 我正在使用Nunit作为测试框架,并使用NMock作为模拟框架。

So far so good. 到现在为止还挺好。

But, can I unit test first two levels of code only mocking Level3 interface without mocking Level2 ? 但是,是否可以仅对模拟Level3接口而不对Level2 Level3对前两个代码级别进行单元测试? I mean I want to unit test class Level1 without mocking Level2 but mocking Level3 . 我的意思是我想在不模拟Level2而是模拟Level3情况下对类Level1进行单元测试。 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. 我之所以想这样做,是因为Level3类从数据库中获取数据,并且我只希望模拟该数据库层,以便我的整个项目只能与模拟db一起使用,而不能与真实数据库一起使用。

That is easy: 很简单:

// arrange
var mocks = new Mockery();
var mockLevel3 = mocks.NewMock<ILevel3>();
// now do some actual mocking here

var level2 = new Level2(mockLevel3);
var level1 = new Level1(level2);

// now do some act and assert stuff

It is an integration test in my opinion. 我认为这是一个集成测试。 It does not matter at this point if all of the classes are in the same assembly. 此时所有类是否都在同一程序集中并不重要。 Integration tests are not necessarily about bringing together some assemblies in a test. 集成测试不一定涉及将某些程序集整合到测试中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM