无法将模拟的Setup方法传入对象列表c#

时间:2018-04-25 09:00:53

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

虽然嘲笑我遇到了一些问题。

 private Mock<IPaymentHandler> _mockRecurringPaymentHandler;
 private Mock<IPaymentHandler> _mockRecurringPaymentFailedHandler;
 private IEnumerable<IPaymentHandler> _paymentManagers;

_mockRecurringPaymentHandler = new Mock<IPaymentHandler>();
_mockRecurringPaymentFailedHandler = new Mock<IPaymentHandler>();

_paymentManagers = new List<IPaymentHandler>
{
    _mockRecurringPaymentHandler.Object,
    _mockRecurringPaymentFailedHandler.Object
};

_sut = new PaypaIIpnManager(
    _paymentManagers,
    _mockLogger.Object
    );

最近我尝试为mockRecurringPaymentHandler设置方法,例如:

_mockRecurringPaymentHandler.Setup(method => method.GetPaymentType()).Returns("GFDGDFGDFG");

它不起作用。它只有在我将它传递给列表之前才能工作。 为什么会出现这种行为?

public PaypaIIpnManager(
            IEnumerable<IPaymentHandler> paymentHandlers,
            ILoggerService<PaypaIIpnManager> logger)
        {
            _handlersDic = RegisterStrategy(paymentHandlers);
            _logger = logger;
        }

protected Dictionary<string, IPaymentHandler> RegisterStrategy(IEnumerable<IPaymentHandler> paymentHandlers)
        {
            var dic = new Dictionary<string, IPaymentHandler>();

            foreach (var handler in paymentHandlers)
            {
                var paymentType = handler.GetPaymentType();

                dic.Add(paymentType, handler);
            }

            return dic;
        }

1 个答案:

答案 0 :(得分:0)

记住单元测试适用于AAA的概念--- Arrange,Act和Assert。在你没有妥善安排事情之前,行为不能按要求行事。

因此,在调用PaypaIIpnManager构造函数时,它会调用您的RegisterStrategy,为您的模拟处理程序调用{​​{1}}。从调用构造函数之前,GetPaymentType未设置为什么在测试中未调用设置方法GetPaymentType。所以在这里,您应该在调用构造函数之前定义GetPaymentType安装程序。