开发者

Mocking filesystem

If my unit tests rel开发者_开发百科y on the file system and I need to mock this, what is the best way to go about this?

Thanks


The file system is an excellent example of how TDD can drive you towards a better, more flexible design. Often, when you interact with the file system, you can deal with reading and writing files using Streams or TextWriters instead of actual files.

These are all abstract types and so are easy to mock.

Now you have a more flexible API because it's not tightly coupled to the file system, but still supports file operations.


You basically have two options: eiter abstract all file-system related logic behind a IFileSystemService, or use Stubs from Microsoft, which is

...a lightweight framework for .NET that provides test stubs. For interfaces and non-sealed classes, type-safe wrappers are generated that can be easily customized by attaching delegates.


This Needed: File system interfaces and implementation in .NET might be useful


Disclaimer I work at Typemock.

I'm glad to say, that our last versions support the following types of System.IO to be mocked:

  • File
  • Directory
  • FileStream

There is a short example:

public void Test()
{
    string path = @"C:\TypemockCan.txt";

    Isolate.WhenCalled(() => File.Exists(null)).WillReturn(true);

    Assert.IsTrue(File.Exists(path));
}

See more examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜