vendredi 8 juillet 2016

Right way to write Unit Tests in C#

Probably going down the rabbit hole, but its worth asking on StackOverflow and getting opinions from experts.

What is the correct way to write a unit test? Specifically, if we have a function to unit test, which in turn calls one or more other functions from the same project... Shall those other two function calls be mocked?

Example:

Unit Test:

[Test]
  public void ReadZipFileContainer_Test()
  {
     AClass aObject = new AClass();
     string fileToRead = System.IO.Path.Combine(Directory.GetCurrentDirectory(), @"..\..\TestData\TestFile.zip");
     List<string> entityIds = new List<string>() { UtilsClass.kItemId };
     Dictionary<string, string> filesData1 = AClass.ReadFileContainer(fileToRead, entityIds);
     Assert.AreEqual(filesData1.Count, 1);
  }

In AClass:

  public Dictionary<string, string> ReadZipFileContainer(string fileToRead, List<string> itemIds)
  {         
     Dictionary<string, string> fileContent = new Dictionary<string, string>();         
     try
     {
        Dictionary<string, string> entities = CClass.OpenContainer(fileToRead); // => call to another function. Should this call be mocked?
        //Process         
     }         
     catch (Exception ex)
     {
        // We return empty directory after closing the container
        logger.LogException(ex);
        throw;
     }
     finally
     {
        CClass.CloseContainer();
     }         
     return fileContent;
  }

Each individual has personal opinion, but I am looking for the best practice. How to decide the line where we need to stop mocking?

Aucun commentaire:

Enregistrer un commentaire