简体   繁体   English

单元测试模拟方法

[英]Unit testing mock method

I am new with unit testing and mock framework. 我是单元测试和模拟框架的新手。

I want to test a method which retrieve data from database and return as a list 我想测试一种从数据库检索数据并作为列表返回的方法

 public virtual List<TemplateClass> GetTemplateist()
 {
    //this is dummy implementation 
      return _templatelist;
 }

here I want to test through mock framework 在这里我想通过模拟框架进行测试

and my test is like this. 我的测试就是这样

[SetUp]
public void TemplateListServiceTestSetUp()
{
    objlsttemplateList = new List<TemplateClass>();
    TemplateClass objtemplateclass = new TemplateClass ();
    objlsttemplateList .Add(objtemplateclass);
    mock = new Mock<TemplateClassService>();
    mock.Setup(x => x.GetTemplatelist()).Returns(objlsttemplateList);
}

[Test]
public void TemplateListServiceTest()
{
    TemplateClassService obj = mock.Object;
    var lst= obj.GetTemplatelist();
}

this obj.GetTemplatelist(); is null. 一片空白。

I am confused about this result.Result is correct or wrong? 我对此result.Result感到困惑。 result.Result是正确还是错误? . Is this is the way by which i am really testing the GetTemplateList() . 这是我真正测试GetTemplateList()的方式GetTemplateList()

Please suggest how i can test the method like this. 请建议我如何测试这种方法。 Thanks in advance. 提前致谢。

The purpose of a mocking framework is to provide implementations for dependencies the code your are testing has so that you can isolate the code you are testing. 模拟框架的目的是为要测试的代码提供依赖项的实现,以便您可以隔离正在测试的代码。

In your example the GetTemplateList() method has no dependencies, and presumably the TemplateClassService class have none either, so mocking is not necessary. 在您的示例中,GetTemplateList()方法没有依赖关系,并且大概TemplateClassService类也没有依赖关系,因此没有必要进行模拟。 You can simply call the method as is to test it and then Assert that you recieved the expected result. 您可以直接按原样调用该方法以对其进行测试,然后断言您已收到预期的结果。

You will need the mocking framework when you replace your dummy implementation with the actual code that retrieves the data from the database. 当用从数据库检索数据的实际代码替换虚拟实现时,将需要模拟框架。 At that time you will probably inject a Repository interface or something similar that takes care of the database calls. 到那时,您可能会注入一个Repository接口或类似的东西来处理数据库调用。 This will then be needed to be mocked so that you don't actually have to have a database connection to test your code. 然后将需要对此进行模拟,以便您实际上不必具有数据库连接即可测试您的代码。

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

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