使用 Moq 框架模拟方法不会返回预期结果 [英] mocking a method using Moq framework doesn't return expected result

查看:59
本文介绍了使用 Moq 框架模拟方法不会返回预期结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类库,它有 2 个类和一个接口,如下所示.
主类:

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 类:

HelperClass Class :

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

界面:

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

现在,我正在尝试测试方法 getData().我已经使用 Moq 模拟了 AddNumbers 方法,如下所示.

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;
 } 

当我调试这个测试时,它返回值 0.
据我了解,当我们模拟任何方法时,它必须在测试时返回模拟值.在这种情况下,我将 AddNumbers 方法的返回值模拟为 8.所以它应该返回 8.但相反,它返回 0.

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 :实际上,Class1 中 ab 的值是动态的.在示例代码中,我对其进行了硬编码.而且,我不想测试 AddNumbers 方法.无论如何,我希望它返回一些固定值.在这种情况下,我希望它返回 8.

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.

推荐答案

您在模拟期望中使用明确的数字指定对 AddNumbers 的调用.只有当这些显式值被赋予 AddNumbers 时,才会返回 8.如果您不关心 AddNumbers 的实际参数,您需要以忽略参数的方式指定您的期望(例如通过 It.IsAny<>)

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);

另见https://github.com/Moq/moq4/wiki/Quickstart 匹配参数"部分.

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

这篇关于使用 Moq 框架模拟方法不会返回预期结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆