Search code examples
c#unit-testingjustmock

Unit Testing : Raise Event From Nested Type


I have an Interface which has a property on another interface,

public interface IInnerInterface
{
    event EventHandler OnCompleted;
}

public class InnerClassImplementation : IInnerInterface
{
    public event EventHandler OnCompleted;

    private void CompletedState()
    {
        OnCompleted?.Invoke(this, new EventArgs());
    }
}

public interface IOuterInterface
{
    IInnerInterface InnerInterface { get; }
}

public class Main : IOuterInterface
{
    public IInnerInterface InnerInterface { get; }

    public bool IsOperationComplete { get; set; }

    public Main(IInnerInterface innerInterface)
    {
        InnerInterface = innerInterface;
        InnerInterface.OnCompleted += InnerInterface_OnCompleted;
    }

    private void InnerInterface_OnCompleted(object sender, EventArgs e)
    {
        IsOperationComplete = true;
    }
}

I am trying to test the Main class. One of the test case is to validate the Handler method for the event.

I tried the following code implementation to test,

[TestClass]
public class MainTest
{
    private Mock<IInnerInterface> _innerInterfaceMock;
    private Main _main;

    [TestInitialize]
    public void Initialize()
    {
        _innerInterfaceMock = new Mock<IInnerInterface>();
        _main = new Main(_innerInterfaceMock.Object);
    }

    [TestMethod]
    public void OnCompleted_ShouldDoSomething()
    {
        //Act
        _main.Raise(m=>m.InnerInterface.OnCompleted+=null, new EventArgs());

        //Assert
        _main.IsOperationComplete.Should().BeTrue();

    }
}

I am getting the following error,

Test method Samples.MainTest.OnCompleted_ShouldDoSomething threw exception: Telerik.JustMock.Core.MockException: Unable to deduce which event was specified in the parameter. at Telerik.JustMock.Core.Behaviors.RaiseEventBehavior.RaiseEventImpl(Object instance, EventInfo evt, Object[] args) at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction) at Samples.MainTest.OnCompleted_ShouldDoSomething()

Don't know what am I doing wrong?


Solution

  • You shouldn't raise the event from your SUT (Main), raise it straight from the IInnerInterface mock:

    _innerInterfaceMock.Raise(o => o.OnCompleted+=null, new EventArgs());
    

    BTW this code (which is based on yours) uses moq not justmock but your exception is justmock related, I assume that using both causes methods and overloads confusions, just pick one and stick with it.