Unit Testing File I/O

后端 未结 6 1780
故里飘歌
故里飘歌 2020-11-29 20:58

Reading through the existing unit testing related threads here on Stack Overflow, I couldn\'t find one with a clear answer about how to unit test file I/O operations. I have

6条回答
  •  半阙折子戏
    2020-11-29 21:30

    Since 2012, you can do that using Microsoft Fakes without the need to change your codebase for example because it was frozen already.

    First generate a fake assembly for System.dll - or any other package and then mock expected returns as in:

    using Microsoft.QualityTools.Testing.Fakes;
    ...
    using (ShimsContext.Create())
    {
         System.IO.Fakes.ShimFile.ExistsString = (p) => true;
         System.IO.Fakes.ShimFile.ReadAllTextString = (p) => "your file content";
    
          //Your methods to test
    }
    

提交回复
热议问题