如何 return 在单元测试中使用最小起订量在异步方法中传递参数?

How to return passed parameters in an async method with Moq in unit tests?

我正在努力解决如何使用 Moq-Setup-Return 构造的问题。

首先,我的设置:

某些 IRepository 类型的存储库-接口必须实现 StoreAsync-方法,其中 returns 包含存储实体 属性 的 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}));
        }
    }
}

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

我在 Moq ReturnsAsync() with parameters and Returning value that was passed into a method 中读到了这个话题。

我试过了

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

错误语句“无法将 lambda 表达式转换为类型“StoreResult”,因为它不是委托类型。

我试过同样的错误信息

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

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

感谢您的帮助。

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

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

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