Search code examples
c#nunit

How to Mock file and File content with NUit


Hello I have the following scenario:

Configuration files are stored in a specific folder (and sub folders), the structure looks something like below, with .conf files containing XML and .conf.json contains JSON

- Config
|- main_config.json
|- in/
   |- mod1.conf
   |- mod2.conf.json
   |- mod3.conf
   |- ...
|- out/ 
   |- mod1.conf.json
   |- mod2.conf
   |- ...

In my project I have a class that encapsulates the existence of these files, such that it is not exposed in the rest of the software. I do not parse a reader or writer of any form (dependency injection, etc) to this class it is all handled internally. In the encapsulation I read the models contained in the configuration files and then validate them using FluentValidation.

Now my issue is I want to test this flow in a unit test, but I cannot find a way to mock the file system, so how to do this? Let me expand a little bit, if I did parse the reader and writer using dependency injection, this is easy. But that is not what I am looking for.


Solution

  • If the encapsulating class handles the writing and writing of the files internally without requesting its dependencies (reader and writer) via DI, writing a unit test will be impossible.
    A unit test is based on the fact that to test this particular unit, all other parts can be mocked away.

    So either abstract the filesystem (e. g. IFileSystem) or write an integration test.