Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mocking a method using Moq framework doesn't return expected result

I have a class library , which has 2 classes and one Interface as below.
Main Class:

    public class Class1 
    {
        int a=5 ,b=9;
        private Interface1 iHelper;
        public Class1(Interface1 _inter)
        {
            iHelper = _inter;
        }
        public int getData()
        {
            int result = iHelper.AddNumbers(a, b);
            return result;
        }

    }

HelperClass Class :

class HelperClass : Interface1
    {
        public int AddNumbers(int a, int b)
        {
            return a + b;
        }
    }

Interface :

public interface Interface1
    {
        int AddNumbers(int a, int b);
    }

Now, I'm trying to test the method getData(). I have mocked AddNumbers method using Moq , as shown below.

[TestMethod()]
public void getDataTest()
{
     int a = 3, b = 5;
     int c = 8;
     var mockService = new Mock<Interface1>();
     mockService.Setup(x => x.AddNumbers(a,b)).Returns(c);

     Class1 obj = new Class1(mockService.Object);
     var result = obj.getData();
     int final = result;
 } 

When I debug this test, it is returning value 0.
As I understand when we mock any method, it has to return the mocked value while testing. In this case I have mocked the return value of AddNumbers method to 8. So it should return 8.But instead , it is returning 0.

Can anyone explain me what am I doing wrong.

EDIT : In reality , the values of a and b in Class1 are dynamic . In the sample code I have hardcoded it. And also , I do not want to test AddNumbers method. I want it to return some fixed value no matter what. In this case, i want it to return 8.

like image 616
CrazyCoder Avatar asked Dec 18 '22 22:12

CrazyCoder


1 Answers

You specify the call to AddNumbers in your mock expectation with explicit numbers. Only when these explicit values are given to AddNumbers will 8 be returned. If you do not care about the actual parameters to AddNumbers you need to specify your expectation in a way that the parameters are ignored (e.g. via It.IsAny<>)

mockService.Setup(x => x.AddNumbers(It.IsAny<int>(),It.IsAny<int>())).Returns(c);

Also see https://github.com/Moq/moq4/wiki/Quickstart section "Matching Arguments".

like image 83
EricSchaefer Avatar answered Dec 20 '22 11:12

EricSchaefer