NSubstitute - 设置调用对象的 属性

NSubstitute - setting a property of the calling object

我有一个问题,我想将起订量完全换成 NSubstitute。在大多数情况下,这非常简单,但是我 运行 遇到了一个相当专业的问题。

这是最小起订量代码。

_registrationCommandHandler.Setup(c => c.Execute
(It.Is<CheckUniqueUserCommand>(r => r.Request.UserName == "fred"))).
                Callback((CheckUniqueUserCommand c) =>
                {
                    c.Response = new CheckUserNameIsUniqueResponse()
                    {
                        IsUnique = true,
                        Success = true
                    };
                    c.Success = true;
                });

我认为最接近 NSubstitute 的是

 _registrationCommandHandler.When(c => c.Execute    
(Arg.Any<CheckUniqueUserCommand>())).Do
            ((CheckUniqueUserCommand c) =>
            {
              c.Response = new __Internal.CheckUserNameIsUniqueResponse()
              {
                  IsUnique = true,
                  Success = true
              };
            c.Success = true;
          });

甚至无法编译。这让我有点卡住了。有人有什么建议吗?

我在这里有点猜测,但试试看:

 _registrationCommandHandler
    .When(c => c.Execute(Arg.Is<CheckUniqueUserCommand>(r => r.Request.UserName == "fred")))
    .Do(call => {
          var c = call.Arg<CheckUniqueUserCommand>();
          c.Response = new __Internal.CheckUserNameIsUniqueResponse()
          {
              IsUnique = true,
              Success = true
          };
          c.Success = true;
    });

NSubstitute 不执行与 Moq does for callbacks. Instead it passes a parameter with information about the call, and you can access the arguments using call.Arg<T> or call[i].

相同的参数传递

除了更改 .Do 块之外,我还从使用 Arg.Any(..) 切换到 Arg.Is(..) 以更接近 Moq 示例。

希望这对您有所帮助。