Skip to content

Question: How to throw Exceptions with FakeItEasy and the MockFileSystem #776

@StarWars999123

Description

@StarWars999123

I have a MockFileSystem describing a file structure and want to check, that thrown IOExceptions during the deletion get catched by my software under test. Unfortunately I am not able to successfully initialize a MockFileSystem and throw a Exception on the call of File.Delete().

Code to test:

public IFileSystem FileSystem; // should be a MockFileSystem for Unit-Tests

public void DeleteUserData(string userId){
    // parses the complete file structure, searches for different files etc. Finally finds the path.
    var path = DoSomeMagicToFindTheCorrectPath(userId);

    if(FileSystem.Directory.Exists(path){

        //This line should throw  an exception!
        FileSystem.Directory.Delete(path, true);
    }

Unittest:

[Test]
public void DeleteFiles([Values(IOException)] type exceptionType){
    var FileSystemStructure = new Dictionary<string, MockFileData>(){
       {"C:\UserDataDir\User1\filea.txt", new MockFileData("fileA")}, 
       {"C:\UserDataDir\User2\filex.txt", new MockFileData("fileX")}
    };

    var fileSystem = A.Fake<MockFileSystem>(options=> options.CallsBaseMethods());
    foreach (var v in FileSystemStructure)
    {
        fileSystem.AddFile(v.Key, v.Value);
    }

    A.CallTo(() => fileSystem.Directory.Delete(@"C:\UserDataDir\User1\").Throws(
        () => (Exception) Activator.CreateInstance(exceptionType)
    );
}

Output during execution:

System.ArgumentException : Object 'System.IO.Abstractions.TestingHelpers.MockDirectory' of type System.IO.Abstractions.TestingHelpers.MockDirectory is not recognized as a fake object.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions