How to return passed parameters in an async method with Moq in unit tests?
<p>I am struggling with the problem of how to use the Moq-Setup-Return construct.</p>
<p>First, my setting:</p>
<p>Some repository of type <code>IRepository</code>-Interface has to implement the <code>StoreAsync</code>-Method that returns a StoreResult object with the stored entity as property included.</p>
<pre><code>using System.Threading.Tasks;
using Moq;
using Xunit;

namespace Tests
{
    public class Entity { }

    public class StoreResult
    {
        public Entity Entity { get; set; }
    }

    public interface IRepository
    {
        Task&lt;StoreResult&gt; StoreAsync(Entity entity);
    }

    public class Tests
    {
        [Fact]
        public void Test()
        {
            var moq = new Mock&lt;IRepository&gt;();
            moq.Setup(m =&gt; m.StoreAsync(It.IsAny&lt;Entity&gt;())).Returns(e =&gt; Task.FromResult&lt;Task&lt;StoreResult&gt;&gt;(new StoreResult {Entity = e}));
        }
    }
}
</code></pre>
<p>Now I try to write a Mock-Objekt for the IRepository-Interface, but I do not know how to code the Return-Statement so that the StoreResult-Object includes the entity given as a parameter to the StoreAsync-Function.</p>
<p>I read about this topic in <a href="https://stackoverflow.com/questions/31527394/moq-returnsasync-with-parameters">Moq ReturnsAsync() with parameters</a> and <a href="https://stackoverflow.com/questions/996602/moq-returning-value-that-was-passed-into-a-method">Returning value that was passed into a method</a>.</p>
<p>I have tried</p>
<pre class="lang-cs prettyprint-override"><code>moq.Setup(m =&gt; m.StoreAsync(It.IsAny&lt;Entity&gt;()))
     .ReturnsAsync(entity =&gt; new StoreResult {Entity = entity});
</code></pre>
<p>with the error statement &quot;Cannot convert lambda expression to type &quot;<code>StoreResult</code>&quot;, because it is not a delegate type.</p>
<p>And with the same error message I tried</p>
<pre class="lang-cs prettyprint-override"><code>moq.Setup(m =&gt; m.StoreAsync(It.IsAny&lt;Entity&gt;()))
     .Returns(e =&gt; Task.FromResult&lt;Task&lt;StoreResult&gt;&gt;(new StoreResult {Entity = e}));
</code></pre>
<p>I am using a .NET Core xUnit environment with <code>Moq 4.6.36-alpha</code></p>
<p>Thank you for your help.</p>