How do I MOQ the System.IO.FileInfo class… or any other class without an interface?

前端 未结 3 899
死守一世寂寞
死守一世寂寞 2020-12-05 13:49

I am writing a number of unit tests for a logger class I created and I want to simulate the file class. I can\'t find the interface that I need to use to create the MOQ...

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 14:13

    Design your code so that instead of accessing the FileInfo class directly, access an interface (named for example IFileInfo) with the same capabilities. In production code you will use a class that just delegates all its functionality to the system FileInfo class, but for unit testing you can mock the interface.

    For example, in an application I made that acted differently depending on the current date, I declared the following interface:

    interface IDateTimeProvider
    {
        DateTime Today();
    }
    

    And the production class was just:

    class DateTimeProvider : IDateTimeProvider
    {
        public DateTime Today()
        {
            return DateTime.Today;
        }
    }
    

    You can complement this approach with the usage of a dependency injection engine to decide whether a real class or a mock should be used in each case.

提交回复
热议问题