How do I mock a class without an interface?

I am working on .NET 4.0 using C# in Windows 7.

I want to test the communication between some methods using mock. The only problem is that I want to do it without implementing an interface. Is that possible?

I just read a lot of topics and some tutorials about mock objects, but all of them used to mock interfaces, and not the classes. I tried to use Rhino and Moq frameworks.


Solution 1:

Simply mark any method you need to fake as virtual (and not private). Then you will be able to create a fake that can override the method.

If you use new Mock<Type> and you don't have a parameterless constructor then you can pass the parameters as the arguments of the above call as it takes a type of param Objects

Solution 2:

Most mocking frameworks (Moq and RhinoMocks included) generate proxy classes as a substitute for your mocked class, and override the virtual methods with behavior that you define. Because of this, you can only mock interfaces, or virtual methods on concrete or abstract classes. Additionally, if you're mocking a concrete class, you almost always need to provide a parameterless constructor so that the mocking framework knows how to instantiate the class.

Why the aversion to creating interfaces in your code?

Solution 3:

With MoQ, you can mock concrete classes:

var mocked = new Mock<MyConcreteClass>();

but this allows you to override virtual code (methods and properties).

Solution 4:

I think it's better to create an interface for that class. And create a unit test using interface.

If it you don't have access to that class, you can create an adapter for that class.

For example:

public class RealClass
{
    int DoSomething(string input)
    {
        // real implementation here
    }
}

public interface IRealClassAdapter
{
    int DoSomething(string input);
}

public class RealClassAdapter : IRealClassAdapter
{
    readonly RealClass _realClass;

    public RealClassAdapter() => _realClass = new RealClass();

    int DoSomething(string input) => _realClass.DoSomething(input);
}

This way, you can easily create mock for your class using IRealClassAdapter.

Hope it works.