Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock .NET classes using wrapper classes

I have a class that takes a MethodInfo instance and extracts some information from it, but I would like to mock this class. At the moment it is difficult because it takes a MethodInfo, so my plan was to create a wrapper for the MethodInfo class and implement an interface on it. For example:

public interface IMethodInfo
{
    string Name { get; }
}

public class MethodInfoProxy : IMethodInfo
{
    private readonly MethodInfo _method;
    public MethodInfoProxy(MethodInfo method)
    {
        _method = method;
    }

    public string Name { get { return _method.Name; } }
}

public class MyClass
{
    public MyClass(IMethodInfo method)
    {
        ...
    }
}

Another example would be the File.Exists method. The thought would be to create a IFile.Exists and put it on a FileProxy class that would simply delegate to File.Exists.

As I'm new to the whole unit testing world I would like to know if this would be considered a good approach to take?

like image 406
MotoSV Avatar asked Oct 12 '22 10:10

MotoSV


1 Answers

You have two options here:

  1. Use a mocking framework like Microsoft Moles or TypeMock Isolator that can mock static and sealed classes. This is great because you don't end up changing your code just to isolate the code under test from its dependencies.
  2. Defining interfaces for behaviours that you want to mock, and then creating a default implementation that wraps a static call, or other difficult-to-test api. This is the approach you've suggested and one that I've used a lot. The key thing, when defining these interfaces is to pass the real/mock implementation of the interface into the test class via some form of dependency injection - usually constructor injection. Some people make the mistake of constructing the object within the class being tested and that makes it impossible to test. A good rule of thumb is that when you see objects being constructed in your business code, then that is a code smell - not always a bad thing, but definitely something to view with suspicion. There's a great video about this stuff: The Clean Code Talks - "Global State and Singletons".

There's a bit of a religious war between those who think testing shouldn't change the code and those that think it should. Dependency injection, which is essential if you are going to mock by creating interfaces, leads to code with high cohesion and loose coupling and an intuitive API. But the other approach isn't precluded from these benefits - it's just not so automatic.

like image 70
sheikhjabootie Avatar answered Oct 15 '22 09:10

sheikhjabootie