Unable to fire event from FakeItEasy in unit test

I am using Test Driven Development to develop a simple application using Xamarin Studio on Mac OS X. I am using NUnit as a test harness and FakeItEasy for mocking. I have developed an object that fires an event and I want to test this response of another object to that event, however it seems that the response object never receives any events, which are fires in the test.

The following code illustrates the problem:

using System;
using NUnit.Framework;
using FakeItEasy;

namespace EventTest
{
    public class EventProvider
    {
        public delegate void EventDelegate(object sender, EventArgs arguments);

        public EventDelegate Event;
    }

    class EventResponder
    {
        public EventResponder(EventProvider provider)
        {
            provider.Event += (sender, arguments) => ++EventCount;
        }

        public uint EventCount { get; private set; }
    }

    [TestFixture]
    public class EventResponderTest
    {
        [Test]
        public void ResponseToFiredEvent()
        {
            var eventProvider = A.Fake<EventProvider>();

            EventResponder responder = new EventResponder(eventProvider);

            eventProvider.Event += Raise.WithEmpty().Now;
            eventProvider.Event += Raise.WithEmpty().Now;
            eventProvider.Event += Raise.WithEmpty().Now;

            Assert.AreEqual(3, responder.EventCount);
        }
    }
}

      

The test fails because EventCount is 0. What do you need to do to pass this test?

+3


source to share


1 answer


Your test fails because FakeItEasy requires fake members to be virtual or more generic - overridden, and the same goes for events that FakeItEasy raises . Your current event is not overridable. To fix this, follow these steps:



  • change Event

    member to virtual ( public virtual event EventDelegate Event;

    )
  • hide the EventProvider

    implementation behind the interface, spoof the interface instead of the class, and make your consumer ( EventResponder

    ) depend on the interface
+1


source







All Articles