繁体   English   中英

起订量具体 class 不使用虚拟关键字

[英]Moq concrete class without using virtual keyword

情况

我这里有以下代码

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)

问题

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

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

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

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

如果你想测试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
}

找到解决方案:姿势

它使用 ILGenerator 并且很旧,但它可以工作。

例子

var test = new Test(); // default value of 'Prop' is  0
var shim = Shim.Replace(() => test.Prop).With((Test @this) => // idk why he needs @this param
{
    return 100; // sets the 'Prop' value to 100
});

var result = 0;
PoseContext.Isolate(() =>
{
    result = test.Calc(); // prints 200;
}, shim);

模拟将被用来替代您尝试测试的依赖项。

关于您的测试,只需测试 class 的实际暴露行为,这意味着不要尝试使用私有方法和设置器。 在任何情况下,模拟 class 进行测试都不是有效的方法。

例如:

如果要测试Test class:

[TestClass]
public class TestTests
{

    [TestMethod]
    public void Calc_WhenPropIsSetTo5_Returns10()
    {
        /**
         *   Seems this is what you want to test (see name of methods),
         *   and I don't think it is a good idea, as your setter is private.
         *   Since it's not a "public" behavior, you could either 
         *
         *    a) have the setter as internal for testing purposes,
         *
         *    b) (my recommendation) go for the two other tests below instead;
         *       this will actually test the exposed behavior of the class.
         *
         *    c) circumvent the accessibility (by using a library or using
         *       Reflection directly) to set the value of the prop. 
         *       See your own answer for an example. 
         */
    }

    [TestMethod]
    public void Calc_WhenCreatedWith5_Returns10()
    {
        // Arrange 
        var testSubject = new Test(5); // if the prop is set by constructor... otherwise arrange in the proper way.

        // Act
        var actualResult = testSubject.Calc();

        // Assert
        Assert.AreEqual(expected: 10, actualResult)
    }

    [TestMethod]
    public void Prop_WhenCreatedWith5_IsSetTo5()
    {
        // Arrange 
        var testSubject = new Test(5);

        // Act
        var actualResult = testSubject.Prop;

        // Assert
        Assert.AreEqual(expected: 5, actualResult)
    }
}

如果你想测试使用ITest.Calc()的东西,

那么你应该在你的实际代码中,

1 -取决于接口ITest ,而不是实现Test

2 - 将依赖注入到正在测试的 class 中,这样您就可以用Mock<ITest>.Object()替换通常的实现Test

public class ClassThatUsesTest
{
    private readonly ITest _test;

    public ClassThatUsesTest(ITest test)
    {
        _test = test;    
    }


    public int SomeFunction()
    { 
       if (_test.Calc() == 10)
       {
           return 42;
       }
       else
       {
           return 0;
       }
    }
}

[TestClass]
public class ClassThatUsesTestTests
{
    [TestMethod]
    public void SomeFunction_WhenTestCalcReturns10_Returns42()
    {
        // Arrange
        var testMock = new Mock<ITest>();
        testMock.Setup(x => x.Calc()).Returns(10);
        var testSubject = new ClassThatUsesTest(testMock.Object);
        var expectedResult = 42;

        // Act
        var actualResult = testSubject.SomeFunction();

        //
        Assert.AreEqual(expectedResult, actualResult);
    }
}

在最后一个示例中,您可以看到模拟帮助我们隔离测试,而不依赖于Test class 的实际实现细节。 即使突然间实际的Test被破坏或改变(例如,你需要通过 6 而不是 5 来获得 10),测试方法并不关心。

虽然这感觉不对,因为它为了测试目的而改变了方法实现,只是为了分享:

public class Test : ITest
{
    private int _prop;

    public int Prop
    {
        get => ((ITest)this).Prop;
        private set => _prop = value;
    }

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

    int ITest.Prop => _prop;
}

在测试中:

var mock = new Mock<Test>();
mock.As<ITest>()
    .Setup(x => x.Prop)
    .Returns(3);

// This should return 6
mock.Object.Calc();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM