From e48f1c6d342084177f35783b448207ec9b7787f2 Mon Sep 17 00:00:00 2001 From: Dominique Schuppli Date: Thu, 12 May 2022 13:45:43 +0200 Subject: [PATCH 1/3] `NullReferenceException` when setting up task `.Result` to return `null` --- .../Regressions/IssueReportsFixture.cs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/Moq.Tests/Regressions/IssueReportsFixture.cs b/tests/Moq.Tests/Regressions/IssueReportsFixture.cs index 428615aef..c4dc04dd2 100644 --- a/tests/Moq.Tests/Regressions/IssueReportsFixture.cs +++ b/tests/Moq.Tests/Regressions/IssueReportsFixture.cs @@ -3802,6 +3802,29 @@ public void No_ArgumentException_due_to_parameter_refness() #endregion + #region 1253 + + public class Issue1253 + { + public interface IFoo + { + Task Bar(); + } + + [Fact] + public async Task Test() + { + var mock = new Mock(); + mock.Setup(x => x.Bar().Result).Returns((string)null); + + var result = await mock.Object.Bar(); + + Assert.Null(result); + } + } + + #endregion + // Old @ Google Code #region #47 From ac4b6897e659df5cd7fd9ea60a0c75f796043d2b Mon Sep 17 00:00:00 2001 From: Dominique Schuppli Date: Thu, 12 May 2022 13:46:22 +0200 Subject: [PATCH 2/3] `null` is a valid `.Result` value, don't exclude it --- src/Moq/Invocation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Moq/Invocation.cs b/src/Moq/Invocation.cs index b859d11f0..d6d52422e 100644 --- a/src/Moq/Invocation.cs +++ b/src/Moq/Invocation.cs @@ -97,7 +97,7 @@ public void ConvertResultToAwaitable(IAwaitableFactory awaitableFactory) { this.result = awaitableFactory.CreateFaulted(r.Exception); } - else if (this.result != null && !this.method.ReturnType.IsAssignableFrom(this.result.GetType())) + else if (!this.method.ReturnType.IsAssignableFrom(this.result?.GetType())) { this.result = awaitableFactory.CreateCompleted(this.result); } From 2cfc109f98d13e7736c0865c43614148afd344a3 Mon Sep 17 00:00:00 2001 From: Dominique Schuppli Date: Thu, 12 May 2022 13:47:37 +0200 Subject: [PATCH 3/3] Update changelog --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1db6d256c..9be8f1824 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file. The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). +## Unreleased + +#### Fixed + +* Difference in behavior when mocking async method using `.Result` vs without (@cyungmann, #1253) + + ## 4.18.0 (2022-05-12) New major version of DynamicProxy (you may get better performance!), so please update with care.