checai
checai

Reputation: 936

c# Mock interface vs mock class

I'm new to the moq framework in .net. From my research online, it seems like there are 2 ways to make use of this framework. Either mock the interface or mock a concrete class. Seems like when mocking concrete class, only virtual method can be mocked. In my case, I just want to mock a couple method of a class which implements an interface.

For example, if we have the following:

public interface Ifoo
{
    int Bar();
}

public class Foo : Ifoo
{
    public virtual int Bar()
    {
        return 0;
    }
}

public class Client
{
    public Client(Ifoo foo)
    {
        var temp = foo.Bar();
    }
}

Now if I need to unit test Client, I need to pass a mocked Ifoo object in the ctor. In this case, should I do:

var mock = new Mock<Ifoo>();

or

var mock = new Mock<Foo>();

Does it make a difference in my case? What's the pros and cons of mocking interface vs mocking class? To me, mocking interface is always a better solution since mocking a class can only give the mock of the virtual method.

Upvotes: 3

Views: 7557

Answers (1)

S.C.
S.C.

Reputation: 1160

Here are some points to consider:

  • Your client consumes IFoo, so that's what you should mock.
  • If your client consumes a concrete class, you should think about refactoring your client to consume the interface or abstract class instead to comply with SOLID principles.
  • If your client consumes a mock of Foo during your test instead of the interface and it relies on some of the non-mocked behavior in that test, you're not really writing a unit test since you're testing the behavior of more than one unit.
  • If your client doesn't consume any non-mocked behavior during the test then you might as well just pass a mock of the interface anyway.

tldr: Classes should consume interfaces or abstract classes rather than concrete classes. Tests should mock interfaces or abstract classes rather than concrete classes.

Upvotes: 7

Related Questions