简体   繁体   English

无法将模拟程序的设置方法传递给对象列表C#

[英]Couldn't Setup method for mock passed into list of objects c#

While mocking I ran into some problems. 在嘲笑时,我遇到了一些问题。

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

And when lately I try to setup a method for mockRecurringPaymentHandler , eg below: 最近,当我尝试为mockRecurringPaymentHandler设置方法时,例如:

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

It doesn't work. 没用 It works only if I do it before passing it to list. 仅当我在将其传递到列表之前执行此操作时,它才有效。 Why does this have such behavior? 为什么会有这种行为?

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

Remember unit testing works on a concept of AAA --- Arrange, Act and Assert. 请记住,单元测试基于AAA的概念-安排,行动和声明。 Until you don't arrange the things appropriately, act does not work as required. 除非您没有妥善安排事情,否则行动将无法按要求进行。

So here when PaypaIIpnManager constructor is invoked then it calls your RegisterStrategy which invokes GetPaymentType for your mocked handler. 因此,在这里,当调用PaypaIIpnManager构造函数时,它将调用您的RegisterStrategyGetPaymentType为您的GetPaymentType处理程序调用GetPaymentType Since before invoking the constructor, the GetPaymentType is not setup that's why in your test the setup method GetPaymentType is not called. 由于在调用构造函数之前,未设置GetPaymentType ,因此在测试中未调用设置方法GetPaymentType So here, you should define the GetPaymentType Setup before you call the constructor. 因此,在这里,您应该在调用构造函数之前定义GetPaymentType安装程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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