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

大城市里の小女人 提交于 2019-11-27 20:28:51
Wim Coenen

Use SystemWrapper, a library which provides interfaces and mockable wrappers classes for many .NET classes which don't implement interfaces themselves.

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.

This might help you to ease the creation of wrapper classes for static or non-mockable 3rd party classes. This tool will generated Interface and a concrete wrapper class of any existing class such as System.IO right on your Visual Studio Project.

https://www.nuget.org/packages/Digitrish.WrapperGenerator/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!