Reputation: 460
I'm trying to use recursive mocking feature from the Moq framework but it doesn't work as I expect it to work.
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);
}
}
}
Could please someone explain to me why SomethingHappened
is never handled? I have an assumption that references of parent.Child.SomethingHappened
and x.Child.SomethingHappened
are not equals. If so then why it's not the same?
Upvotes: 3
Views: 529
Reputation: 1504
It's all correct, you need the following:
[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);
}
Upvotes: 1