Mocking filesystem
Asked Answered
M

4

9

If my unit tests rely on the file system and I need to mock this, what is the best way to go about this?

Thanks

Minutiae answered 15/2, 2010 at 14:36 Comment(4)
If you're actually talking about Typemock you shouldn't have an issue as Typemock can mock any type, including sealed types.Porism
Chanting "your filesystem is worthless and weak" is a good way to mock them...Byrnie
I thought thatTypemock couldn't mock things in mscorlib, which a lot of this is in. Except maybe DateTime.Now. Maybe.Frenchpolish
@Sam - You're correct. TypeMock cannot mock objects in mscrolib, but they did find a way to mock DateTime during the research into the Racer product.Mortimer
R
3

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.

Revulsion answered 15/2, 2010 at 14:39 Comment(0)
J
9

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.

Jaramillo answered 15/2, 2010 at 14:52 Comment(1)
+1, using streams is great because you stay compatible with all sorts of input/output devices.Dagon
R
3

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.

Revulsion answered 15/2, 2010 at 14:39 Comment(0)
F
1

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

Frenchpolish answered 15/2, 2010 at 14:55 Comment(0)
M
1

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.

Missive answered 16/2, 2016 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.