首页 > 解决方案 > 不使用 virtual 关键字的 Moq 具体类

问题描述

情况

我这里有以下代码

ITest.cs

public interface ITest
{
    int Prop { get; }
    int Calc();
}

测试.cs

public class Test : ITest
{
    public int Prop { get; private set; }

    public int Calc()
    {
        return Prop * 2;
    }
}

我想测试这个Calc()方法。如果我的理解是正确的,您不能在不使用virtual关键字的情况下覆盖具体类的 getter 属性。

例如

var moq = new Mock<Test>();  // mocked Test class
moq.Setup(x => x.Prop).Returns(2); // throws an error, 
                                   // however with "virtual int Prop { get; }" it doesn't throw any exceptions
var moq = new Mock<ITest>();  // mocked ITest interface
moq.Setup(x => x.Prop).Returns(2); // works fine
                                   // but can not really test the Calc() method (it returns 0
                                   // because the proxy doesn't have Test's implementation)

问题

所以我的问题是:如何在Calc()不制作的情况下测试virtual int Prop

顺便说一句...这也不起作用

var moq = new Mock<ITest>();
moq.Setup(x => x.Prop).Returns(2);

var obj = (Test)moq.Object; // can NOT convert ITestProxy to Test

标签: c#unit-testingmoq

解决方案


如果你想测试Calc()然后测试Calc()。你不需要嘲笑任何东西

[TestMethod]
public void Test_Calc_DoublesProp()
{
    //arrange           
    var test = new Test(5);  //assumes Prop value can be injected in constructor

    //act
    int result = test.Calc();

    //assert
    Assert.IsTrue(result == 10); // 5 * 2
}

推荐阅读