Search code examples
fakeiteasy

Strict fake forces event subcriptions to be configured in FakeItEasy 7.0


When I am using strict fake with event handlers subscriptions, those are reported as not configured in FakeItEasy 7.0.

  • When fake is strict, an exception is thrown - 'Call to unconfigured method of strict fake: IFoo.add_MyEvent(value: System.EventHandler)'.
  • I can uncomment A.CallTo configuration. But then the test doesn't pass. Putting MustHaveHappened instead of DoesNothing brings another exception - 'Expected to find it once or more but no calls were made to the fake object'.
  • When I remove strict configuration and let the configuraiton commented, test passes.

How should I configure the fake as strict, but handle events in the same time?

var foo = A.Fake<IFoo>(c => c.Strict());
A.CallTo(foo).Where(call => call.Method.Name == "add_MyEvent").MustHaveHappened();
var bar = new Bar(foo);
foo.MyEvent += Raise.With(foo, new EventArgs());
Assert.That(bar.EventCalled, Is.True);

public interface IFoo
{
    event EventHandler MyEvent;
}

public class Bar
{
    public Bar(IFoo foo)
    {
        foo.MyEvent += (o, s) => { EventCalled= true;};
    }

    public bool EventCalled { get; private set; } = false;
}

Solution

  • You can do this:

    var foo = A.Fake<IFoo>(c => c.Strict());
    EventHandler handler = null;
    A.CallTo(foo).Where(call => call.Method.Name == "add_MyEvent")
        .Invokes((EventHandler value) => handler += value);
    var bar = new Bar(foo);
    handler?.Invoke(foo, EventArgs.Empty);
    Assert.That(bar.EventCalled, Is.True);
    

    Note that when you handle event subscription manually, you can no longer use Raise to raise the event, but you can just invoke the delegate manually.


    EDIT: This workaround wasn't necessary with FakeItEasy 6.x... Looks like 7.0 introduced an unintended breaking change. I'll look into it.


    EDIT2: Actually, the breaking change had been anticipated, I had just forgotten about it. The workaround I proposed is actually described in the documentation