gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:44:44 25 4
gpt4 key购买 nike

我正在尝试使用 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);
}

关于c# - 在 Moq 中处理递归创建的 Mock 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29128328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com