简体   繁体   中英

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? . Is this is the way by which i am really testing the 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. 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. This will then be needed to be mocked so that you don't actually have to have a database connection to test your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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