如何在Moq输入参数的属性中调用Action set

时间:2015-12-18 20:48:11

标签: c# .net moq

我在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?

1 个答案:

答案 0 :(得分:2)

如果注入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();
                } });
            }
        }
    }
}