Search code examples
c#unit-testingmockingnunit

moq setup not returning expected value


i am using Nunit and Autofac's Moq to setup a test

    [TestFixture]
public class SomeTests
{

    [OneTimeSetUp]
    public void Initialize()
    {

    }
    [Test]
    public void SalaryCheck()
    {                              
        using (var mock = AutoMock.GetLoose())
        {
            // Arrange
            mock.Mock<ICommonServices>().Setup(x => x.AddTwoNumbers(1,2)).Returns(5);
            var sut = mock.Create<SomeManager>(); 
            // Act
            int actul = sut.CalculateSalary(1);


            var expected = 5;


            // Assert
            Assert.AreEqual(expected, actul);

        }
    }
}

CalculateSalary function looks like this

  public int CalculateSalary(int hours)
    {
        var addres = _commonService.AddTwoNumbers(5,3);
        if (addres == 5)
        {
            return addres * hours;
        }
        else
        { 
            return  100;
        }
    }

i want AddTwoNumbers function which is a external dependency, to return 5 no matter what. thats why i am setting it up after mocking it. But when i debug this test it looks like it goes inside the calsulate salary function but returns a "0" for AddTwoNumbers function. which is kind of a default or a null value.

it does not return me 5 i.e. what i set it up to return.


Solution

  • You need to use It.IsAny<int>() i.e.

    mock.Mock<ICommonServices>().Setup(x => x.AddTwoNumbers(It.IsAny<int>(),It.IsAny<int>())).Returns(5);