Renato Leite
Renato Leite

Reputation: 791

.NET MOQ returning a different result

I'm trying to do a simple test, mocking the sum method.

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. Why this happens?

Upvotes: 0

Views: 48

Answers (1)

Eris
Eris

Reputation: 7638

In your Setup you say IsAny(1,2), those arguments don't match the arguments on Execute which are 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)

Upvotes: 2

Related Questions