Reputation: 103770
A bit of code:
public interface IMyInterface
{
int GetIt();
}
public class MyImplementation : IMyInterface
{
public int GetIt()
{
return 10;
}
}
[Test]
public void Testit()
{
Method<MyImplementation>();
}
private void Method<T>()
where T : class , IMyInterface
{
var mock = new Mock<T>();
mock.Setup(m => m.GetIt()).Returns(() =>
{
return 40;
});
Assert.AreEqual(40, mock.Object.GetIt());
}
Notice that when newing up the Mock I'm using the generic T, however since T is constrained to being a reference type and of type IMyInterface
, I can set up the methods no problem. For some reason though, it always fails, and calls the actual implementation of MyImplementation
as opposed to the Mocked one.
Upvotes: 4
Views: 190
Reputation: 109037
You are essentially mocking a class method and for that the method has to be virtual.
Try
public class MyImplementation : IMyInterface
{
public virtual int GetIt()
{
return 10;
}
}
Upvotes: 4