【问题标题】:Weird issue with Moq when trying to use Mock<T> for a generic type尝试将 Mock<T> 用于泛型类型时,Moq 的奇怪问题
【发布时间】:2011-10-05 23:17:24
【问题描述】:

一点代码:

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());
    }

请注意,在更新 Mock 时,我使用的是泛型 T,但是由于 T 被限制为引用类型和 IMyInterface 类型,因此我可以毫无问题地设置方法。但由于某种原因,它总是失败,并调用 MyImplementation 的实际实现,而不是 Mocked 的实现。

【问题讨论】:

    标签: c# moq


    【解决方案1】:

    您实际上是在模拟一个类方法,因此该方法必须是虚拟的。

    试试

    public class MyImplementation : IMyInterface
    {
        public virtual int GetIt()
        {
            return 10;
        }
    }
    

    【讨论】:

    • 哈哈!!当你想到它时,它是如此明显。好电话!
    • 我只是好奇,为什么我没有得到异常。通常对于 Moq,当您尝试检测非虚拟方法时,它会抛出“NotSupportedException”。
    • @BFree 看看this answer 是否解释了为什么它没有出错,但为什么它没有按照您的预期做。
    猜你喜欢
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多