Skip to content

Commit

Permalink
Merge pull request #2034 from thomaslevesque/fix-null-event-handler
Browse files Browse the repository at this point in the history
Fix event subscription/unsubscription with null handler
  • Loading branch information
blairconrad committed Jun 19, 2024
2 parents 87511a7 + bc16732 commit 94caef0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/FakeItEasy/Core/EventCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ public static bool TryGetEventCall(IFakeObjectCall fakeObjectCall, [NotNullWhen(
return false;
}

eventCall = new EventCall(eventInfo, fakeObjectCall.Method, (Delegate)fakeObjectCall.Arguments[0]!);
var handler = fakeObjectCall.Arguments.Get<Delegate>(0);
if (handler is null)
{
return false;
}

eventCall = new EventCall(eventInfo, fakeObjectCall.Method, handler);
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class DerivedReferenceType : ReferenceType
{
}

public class EventRaisingSpecs
public class EventSpecs
{
private readonly EventArgs eventArgs = new EventArgs();

Expand Down Expand Up @@ -526,5 +526,31 @@ public void RaisingInternalEvent(ClassWithInternalEventVisibleToDynamicProxy fak
"Then the handler is called"
.x(() => A.CallTo(handler).MustHaveHappened());
}

[Scenario]
public void SubscribeWithNullHandler(IEvents fake, Exception? exception)
{
"Given a fake with an event"
.x(() => fake = A.Fake<IEvents>());

"When subscribing to the event with a null handler"
.x(() => exception = Record.Exception(() => fake.UnsubscribedEvent += null));

"Then it should not throw"
.x(() => exception.Should().BeNull());
}

[Scenario]
public void UnsubscribeWithNullHandler(IEvents fake, Exception? exception)
{
"Given a fake with an event"
.x(() => fake = A.Fake<IEvents>());

"When unsubscribing from the event with a null handler"
.x(() => exception = Record.Exception(() => fake.UnsubscribedEvent -= null));

"Then it should not throw"
.x(() => exception.Should().BeNull());
}
}
}

0 comments on commit 94caef0

Please sign in to comment.