4

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.

BFree
  • 102,548
  • 21
  • 159
  • 201

1 Answers1

4

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;
    }
}
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • Haha!! So obvious when you think about it. Good call! – BFree Oct 05 '11 at 15:15
  • I'm just curious, why am I not getting an exception. Usually with Moq, when you try to instrument a method that's not virtual, it throws a "NotSupportedException". – BFree Oct 05 '11 at 15:54
  • @BFree see if [this answer](http://stackoverflow.com/questions/5877546/moq-requirements-defeats-the-purpose/5877676#5877676) explains why it does not error but why it does not do what you expect it to do. – Bala R Oct 05 '11 at 17:37