如何调用Moq输入参数属性中的Action集合

本文关键字:属性 参数 集合 Action 输入 Moq 何调用 调用 | 更新日期: 2023-09-27 18:27:31

我在ViewModel中有以下方法。

public void ViewModelMethod()
        {
            UserDialogs.Confirm(new ConfirmConfig
            {
                Message = "Dialog message",
                OnConfirm = (result) =>
                {
                    if (result)
                    {
                        AnotherService.Method();
                    }
                }
            });
        }

在我的测试中,我有UserDialogsMock和AnotherServiceMock。我正在尝试设置UserDialogsMock,如下所示。

UserDialogsMock.Setup(s => s.Confirm(It.IsAny<ConfirmConfig>()))
                .Callback((ConfirmConfig confirmConfig) => confirmConfig.OnConfirm(true));

如何验证是否调用了AnotherServiceMock.Method?

如何调用Moq输入参数属性中的Action集合

如果AnotherServiceMock被注入,只需验证其正常:

AnotherServiceMock.Verify(s => s.Method(), Times.Once());

这是一个适用于我的SSCCE:

namespace ConsoleApplication
{
    using System;
    using Moq;
    using NUnit.Framework;
    public class MoqCallbackTest
    {
        [Test]
        public void TestMethod()
        {
            Mock<IAnotherService> mockAnotherService = new Mock<IAnotherService>();
            Mock<IUserDialogs> mockUserDialogs = new Mock<IUserDialogs>();
            mockUserDialogs.Setup(s => s.Confirm(It.IsAny<ConfirmConfig>()))
                           .Callback((ConfirmConfig confirmConfig) => confirmConfig.OnConfirm(true));
            SystemUnderTest systemUnderTest = new SystemUnderTest(mockUserDialogs.Object, 
                                                                  mockAnotherService.Object);
            systemUnderTest.ViewModelMethod();
            mockAnotherService.Verify(p => p.Method(), Times.Never());
        }
        public interface IAnotherService
        {
            void Method();
        }
        public interface IUserDialogs
        {
            void Confirm(ConfirmConfig config);
        }
        public class ConfirmConfig
        {
            public Action<bool> OnConfirm { get; set; }
        }
        public class SystemUnderTest
        {
            readonly IAnotherService anotherService;
            readonly IUserDialogs userDialogs;
            public SystemUnderTest(IUserDialogs userDialogs, IAnotherService anotherService)
            {
                this.userDialogs = userDialogs;
                this.anotherService = anotherService;
            }
            public void ViewModelMethod()
            {
                userDialogs.Confirm(new ConfirmConfig { OnConfirm = result =>
                {
                    if (result)
                        anotherService.Method();
                } });
            }
        }
    }
}