diff --git a/Source/Mockolate/MockRegistration.cs b/Source/Mockolate/MockRegistration.cs index 3a8e7859..b3051cc3 100644 --- a/Source/Mockolate/MockRegistration.cs +++ b/Source/Mockolate/MockRegistration.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Linq; using System.Reflection; +using System.Runtime.ExceptionServices; using System.Text; using Mockolate.Exceptions; using Mockolate.Interactions; @@ -78,11 +79,13 @@ public MethodSetupResult InvokeMethod(string methodName, $"The method '{methodName}({string.Join(", ", parameters.Select(x => x.Value?.GetType().FormatType() ?? ""))})' was invoked without prior setup."); } - return new MethodSetupResult(null, Behavior, defaultValue(parameters.Select(x => x.Value).ToArray())); + return new MethodSetupResult(null, Behavior, + defaultValue(parameters.Select(x => x.Value).ToArray())); } return new MethodSetupResult(matchingSetup, Behavior, - matchingSetup.Invoke(methodInvocation, Behavior, () => defaultValue(parameters.Select(x => x.Value).ToArray()))); + matchingSetup.Invoke(methodInvocation, Behavior, + () => defaultValue(parameters.Select(x => x.Value).ToArray()))); } /// @@ -176,7 +179,14 @@ public void Raise(string eventName, params object?[] parameters) { foreach ((object? target, MethodInfo method) in GetEventHandlers(eventName)) { - method.Invoke(target, parameters); + try + { + method.Invoke(target, parameters); + } + catch (TargetInvocationException ex) when (ex.InnerException is not null) + { + ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); + } } } diff --git a/Tests/Mockolate.Tests/MockEvents/RaiseTests.cs b/Tests/Mockolate.Tests/MockEvents/RaiseTests.cs index dad18c0a..971cb8ec 100644 --- a/Tests/Mockolate.Tests/MockEvents/RaiseTests.cs +++ b/Tests/Mockolate.Tests/MockEvents/RaiseTests.cs @@ -96,6 +96,26 @@ public async Task WhenSubscribedToOtherEvent_ShouldNotTrigger() await That(callCount).IsEqualTo(0); } + [Fact] + public async Task WhenSubscriptionThrows_ShouldNotWrapException() + { + IMyEventService mock = Mock.Create(); + + mock.SomeEvent += SubscriptionThrowingException; + + void Act() + { + mock.RaiseOnMock.SomeEvent(this, "event data"); + } + + await That(Act).Throws().WithMessage("Subscription exception"); + + void SubscriptionThrowingException(object? sender, string e) + { + throw new MockException("Subscription exception"); + } + } + [Fact] public async Task WhenUnsubscribedFromOtherEvent_ShouldNotAffectOtherSubscriptions() {