【问题标题】:Using C# Moq testing getting Parameter count mismatch?使用 C# Moq 测试获取参数计数不匹配?
【发布时间】:2019-08-07 01:09:41
【问题描述】:

我知道有类似的问题,但不知何故我无法弄清楚我的情况。我收到参数计数不匹配异常。

这是我注册 Mock 的方式,

    var couponService = 
     DependencyResolver.Resolve<Mock<ICouponWebServiceAdapter>>();
        couponService.Setup(a => 
     a.checkCouponAvailability(It.IsAny<orderLine[]>(), 
            It.IsAny<orderHeader>()))
            .Returns((couponDetail[] request) =>
            {

                var coupon = new couponDetail
                {
                    description = "75% off the original price",
                    value = 50
                };

                var coupon1 = new couponDetail
                {
                    description = "500 off the original price",
                    value = 20
                };

                var coupondetails = new couponDetail[] { coupon, coupon1 };
                return coupondetails;
            });

checkCouponAvailability 正在返回 couponDetail[]

我做错了什么?我试着把我的回报作为 IQueryable

【问题讨论】:

  • 你能发布checkCouponAvailability的方法签名吗?没有深入了解代码,这里很难提供帮助。
  • 您需要提供minimal reproducible example。

标签: c# .net wpf unit-testing moq


【解决方案1】:

似乎在Returns 方法内部指定了一个名为request 类型为couponDetail[] 的参数,但该方法本身采用(orderLine[], orderHeader) 的参数。传递到 Returns 的方法会使用传递给您的模拟方法的实际参数调用,这将导致您得到的 ParameterCountMismatchException。

  1. 您可以在模拟函数之前通过模拟返回来传入所需的文字对象。示例如下:
var coupondetails = new couponDetail[] {
    new couponDetail
    {
        description = "75% off the original price",
        value = 50
    },
    new couponDetail
    {
        description = "500 off the original price",
        value = 20
    }
};
var couponService = DependencyResolver.Resolve<Mock<ICouponWebServiceAdapter>>();

couponService
    .Setup(a => a.checkCouponAvailability(It.IsAny<orderLine[]>(), It.IsAny<orderHeader>()))
    .Returns(coupondetails);
  1. 您可以将方法传递给返回,该方法必须采用传递给原始方法的所有参数。示例如下:
var couponService = DependencyResolver.Resolve<Mock<ICouponWebServiceAdapter>>();

couponService
    .Setup(a => a.checkCouponAvailability(It.IsAny<orderLine[]>(), It.IsAny<orderHeader>()))
    .Returns((orderLine[] arg1, orderHeader arg2) => {
        return new couponDetail[] {
            new couponDetail
            {
                description = "75% off the original price",
                value = 50
            },
            new couponDetail
            {
                description = "500 off the original price",
                value = 20
            }
        };
    });

【讨论】:

  • 5 分钟前才发现它是第一个选项。非常感谢您的帮助!
猜你喜欢
  • 2016-09-21
  • 2011-12-04
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多