Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

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

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... so how do you successfully MOQ a class without an interface?

It also isn't clear to me how I can use dependency injection without having an interface available:

private FileInfo _logFile;

public LogEventProcessorTextFile(FileInfo logFile) {
    _logFile = logFile;
}

When I really want to do something like this (note IFileInfo instead of FileInfo):

private IFileInfo _logFile;

public LogEventProcessorTextFile(IFileInfo logFile) {
    _logFile = logFile;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...