Search code examples
c#visual-studio-2017mockingnsubstitute

NSubstitute Mock static class and static method


I'm trying to mock a static method in a static class. I already read that you can't do that, but I was looking a way to work around that.

I can't modify the code, and making the same function without being static is not an option because they check the code coverage of the test, and I need at least 90%.
I already tried to mock the variables that it uses but it doesn't work.

public static class MyClass
{
    public static response MyMethod(HttpSessionStateBase Session, 
        otherVariable, stringVariable)
    {
        //some code
    }
}

public ActionResult MyClassTested()
{
    var response = MyClass.MyMethod(Session);
    //more code
}

My problem is that this method is inside a controller that declares a var with the response, and according to that redirects the user.


Solution

  • If you can't modify the code then I don't think it is possible to work around this using DynamicProxy-based libraries like NSubstitute. These libraries use inheritance to intercept members on classes, which is not possible for static and non-virtual members.

    I suggest trying Fakes. One of the examples on that page covers stubbing DateTime.Now.

    Other alternatives that can mock static members include TypeMock and Telerik JustMock.

    Related question: https://stackoverflow.com/q/5864076/906