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