使用C#Moq测试得到参数计数不匹配?

时间:2019-03-15 22:17:21

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

我知道也有类似的问题,但是不知何故我无法确定自己的情况。我收到了Paramater计数不匹配异常。

这是我注册模拟游戏的方式,

    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

1 个答案:

答案 0 :(得分: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
            }
        };
    });