Reputation: 936
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
Reputation: 1160
Here are some points to consider:
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