Mocking Static methods using Rhino.Mocks



4 Answers

Wrap the static method call in a virtual instance method in another class, then mock that out.

Question

Is it possible to mock a static method using Rhino.Mocks? If Rhino does not support this, is there a pattern or something which would let me accomplish the same?




You should create a wrapper service called IFileService, then you can create a concrete that uses the statics for use in your app, and a mock IFileService that will have fake functionality for testing. Make it so you have to pass IFileService into the constructor or a property for what ever class is using it, this way normal operation requires you pass in the IFileService. Remember in Unit Testing you are testing just that part of code not the things its calling to like IFileService.

interface IFileService
{
    bool Exists(string fileName);
    void Delete(string fileName);
}

class FileService : IFileService
{
    public bool Exists(string fileName)
    {
        return File.Exists(fileName);
    }

    public void Delete(string fileName)
    {
        File.Delete(fileName);
    }
}

class MyRealCode
{
    private IFileService _fileService;
    public MyRealCode(IFileService fileService)
    {
        _fileService = fileService;
    }
    void DoStuff()
    {
        _fileService.Exists("myfile.txt");
    }
}






Mock File IO static class in c#

You can't mock static methods with Rhino mock. See this question for more info. You could create a facade class to wrap the file system calls you will use and then create a mock version of that.




You could write or using an existing wrapper for the static class (in the case above maybe System.IO.Abstractions will help).




Related



Tags