开发者

Weird issue with Moq when trying to use Mock<T> for a generic type

A bit of code:

public interface IMyInterface
{
    in开发者_运维问答t 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.


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜