如何在单元测试中使用Moq在异步方法中返回传递的参数?

Ral*_*ing 4 c# unit-testing moq .net-core

我对如何使用Moq-Setup-Return构造的问题感到困惑.

首先我的设置:

某些类型为IRepository-Interface的存储库必须实现StoreAsync-Method,该方法返回StoreResult对象,并将存储的实体作为属性包含在内.

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<StoreResult> StoreAsync(Entity entity);
    }

    public class Tests
    {
        [Fact]
        public void Test()
        {
            var moq = new Mock<IRepository>();
            moq.Setup(m => m.StoreAsync(It.IsAny<Entity>())).Returns(e => Task.FromResult<Task<StoreResult>>(new StoreResult {Entity = e}));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我尝试为IRepository-Interface编写一个Mock-Objekt,但我不知道如何编写Return-Statement,以便StoreResult-Object包含作为StoreAsync-Function参数给出的实体.

我在Moq ReturnsAsync()中读到了有关参数MOQ的这个主题:返回传递给方法的值.

我试过了

moq.Setup(m => m.StoreAsync(It.IsAny<Entity>()))
     .ReturnsAsync(entity => new StoreResult {Entity = entity});
Run Code Online (Sandbox Code Playgroud)

使用错误语句"无法将lambda表达式转换为类型" StoreResult",因为它不是委托类型.

并尝试相同的错误消息

moq.Setup(m => m.StoreAsync(It.IsAny<Entity>()))
    .Returns(e => Task.FromResult<Task<StoreResult>>(new StoreResult {Entity = e}));
Run Code Online (Sandbox Code Playgroud)

我正在使用.NET Core xUnit环境 Moq 4.6.36-alpha

谢谢您的帮助.

Ral*_*ing 7

感谢Callum Linigton的提示,我得出了以下解决方案:

moq
 .Setup(m => m.StoreAsync(It.IsAny<Entity>()))
 .Returns((Entity e) => Task.FromResult(new StoreResult {Entity = e}));
Run Code Online (Sandbox Code Playgroud)

关键的区别是指定lambda表达式的输入参数的类型,以避免模糊调用.