Mocking std::fs for unit tests

Hi,
I have a piece of code that walks over some directories and reads some files.
I am trying to write some tests and I am struggling to find an appropriate fs mocking procedure.
All the fs access in Rust is built on top of std::fs which is a module, not a trait or any other kind of interface, so there is no real way to substitute std::fs by std::mock_fs or something like that for the tests.
Creating tempdirs and all that is fine for integration tests, but I don’t think I should be relying on local fs for unit tests.
Somebody must have seen this issue before, how do people deal with this?

You might want to try the tempfile crate:
https://docs.rs/tempfile/3.0.4/tempfile/fn.tempdir.html

With that you can create individual files or directories, and they will be deleted when the object goes out of scope. I think the crate also defaults to using the OS’s designated temporary directories, e.g./tmp/ on linux, which is usually a tmpfs/ramdisk.

Alternatively, the types from std::fs implement several traits over which you might be able to abstract, e.g. Read, Write, Seek:
https://doc.rust-lang.org/std/fs/struct.File.html#implementations

1 Like