Skip to content

Commit 0ddfdb8

Browse files
committed
Returns(InvocationFunc) shouldn't throw TargetInvocationException
1 parent f36d3e8 commit 0ddfdb8

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1
1919
* `AmbiguousMatchException` raised when interface has property indexer besides property in VB. (@mujdatdinc, #1129)
2020
* Interface default methods are ignored (@hahn-kev, #972)
2121
* Callback validation too strict when setting up a task's `.Result` property (@stakx, #1132)
22+
* `setup.Returns(InvocationFunc)` wraps thrown exceptions in `TargetInvocationException` (@stakx, #1141)
2223

2324

2425
## 4.16.0 (2021-01-16)

src/Moq/MethodCall.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ public void SetReturnComputedValueBehavior(Delegate valueFactory)
247247
}
248248
else if (IsInvocationFunc(valueFactory))
249249
{
250-
this.returnOrThrow = new ReturnComputedValue(invocation => valueFactory.DynamicInvoke(invocation));
250+
this.returnOrThrow = new ReturnComputedValue(invocation => valueFactory.InvokePreserveStack(new object[] { invocation }));
251251
}
252252
else
253253
{

tests/Moq.Tests/CallbacksFixture.cs

+13
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,19 @@ public void CallbackWithMultipleArgumentIndexerSetterWithoutAny()
516516
Assert.Equal(2, result);
517517
}
518518

519+
[Fact]
520+
public void Type_of_exception_thrown_from_InvocationFunc_callback_should_be_preserved()
521+
{
522+
var mock = new Mock<IFoo>();
523+
mock.Setup(m => m.Submit("good", "bad")).Returns(new InvocationFunc(invocation =>
524+
{
525+
throw new Exception("very bad"); // this used to be erroneously wrapped as a `TargetInvocationException`
526+
}));
527+
528+
var ex = Assert.Throws<Exception>(() => mock.Object.Submit("good", "bad"));
529+
Assert.Equal("very bad", ex.Message);
530+
}
531+
519532
public interface IInterface
520533
{
521534
void Method(Derived b);

0 commit comments

Comments
 (0)