简体   繁体   中英

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.

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 (eg 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".

Because in Class1 variables a and b differ from variables defined in getDataTest . Use the same values:

[TestMethod()]
public void getDataTest()
{
     int a = 5, b = 9; // here
     int c = 14; // and here
     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;
 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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