在 Moq 中处理递归创建的 Mock 事件

Handling event of recursively created Mock in Moq

我正在尝试使用 Moq 框架中的递归模拟功能,但它无法正常工作。

using System;
using NUnit.Framework;
using Moq;

namespace MoqTest
{
    public interface IParent
    {
        IChild Child { get; }
    }

    public interface IChild
    {
        event EventHandler SomethingHappened;
    }

    [TestFixture]
    public class UnitTest
    {
        [Test]
        public void RecursiveMockTest()
        {
            // Arrange
            bool isEventHandled = false;

            var parentMock = new Mock<IParent>();
            parentMock.DefaultValue = DefaultValue.Mock;

            var parent = parentMock.Object;
            parent.Child.SomethingHappened +=
                (sender, args) =>
                {
                    isEventHandled = true;
                };

            // Act
            parentMock.Raise(x => x.Child.SomethingHappened += null, EventArgs.Empty);

            // Assert
            Assert.IsTrue(isEventHandled);
        }
    }
}

有人可以向我解释为什么 SomethingHappened 从未被处理过吗?我假设 parent.Child.SomethingHappenedx.Child.SomethingHappened 的引用不相等。如果是,那为什么不一样?

一切正确,您需要以下内容:

[Test]
public void RecursiveMockTest()
{
    // Arrange
    bool isEventHandled = false;

    var parentMock = new Mock<IParent>();
    parentMock.DefaultValue = DefaultValue.Mock;

    var parent = parentMock.Object;

    // get the actual mock which was automatically setup for you
    var childMock = Mock.Get(parent.Child);

    parent.Child.SomethingHappened +=
        (sender, args) =>
        {
            isEventHandled = true;
        };

    // Act on the mock which was setup for you
    childMock.Raise(x => x.SomethingHappened += null, EventArgs.Empty);

    // Assert
    Assert.IsTrue(isEventHandled);
}