简体   繁体   English

.NET MOQ返回不同的结果

[英].NET MOQ returning a different result

I'm trying to do a simple test, mocking the sum method. 我正在尝试做一个简单的测试,嘲笑sum方法。

I have an interface: 我有一个界面:

public interface ISumSomething
{
    int Sum(params int[] values);
}

A class that use this interface: 使用此接口的类:

public class CallSum
{
    public CallSum(ISumSomething sumSomething)
    {
        this.SumSomething = sumSomething;
    }

    private ISumSomething SumSomething { get; set; }

    public int Execute(params int[] values)
    {
        return this.SumSomething.Sum(values);
    }
}

And the test class: 和测试类:

    [TestMethod]
    public void Test_Sum_Method()
    {
        // Creates MOQ.
        var instance = new Mock<ISumSomething>();

        // Setup de MOQ.
        instance.Setup(moq => moq.Sum(It.IsAny(1,2)).Returns(4));

        // Instance the object.
        var sum = new CallSum(instance.Object);

        // Execute the operation.
        var result = sum.Execute(2, 2);

        // Check the result.
        Assert.AreEqual(4, result);
    }

The problem is, when I call the Execute method, it is returing 0 , but in my MOQ, I'm setting 4 . 问题是,当我调用Execute方法时,它恢复为0 ,但是在我的最小起订量中,我将设置为4 Why this happens? 为什么会这样?

In your Setup you say IsAny(1,2) , those arguments don't match the arguments on Execute which are 2,2 Setup您说IsAny(1,2) ,这些参数与Execute上的参数2,2不匹配

You should instead be using: 您应该改为使用:

    instance.Setup(moq => moq.Sum(It.IsAny<int[]>()).Returns(4));

(See Setup Method With Params Array for more info) (有关更多信息,请参见使用参数数组的设置方法

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

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