2016-08-01 41 views
2

我很困扰如何使用Moq-Setup-Return构造。如何在单元测试中使用Moq在异步方法中返回传递的参数?

首先我的设置:

IRepository类型的一些库-Interface必须实现StoreAsync - 方法为包括属性,它返回一个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})); 
     } 
    } 
} 

现在我试着写一个实体模型OBJEKT为IRepository接口,但是我不知道如何使StoreResult,对象包括给定的参数为StoreAsync-实体编码的返回,声明功能。

我在Moq ReturnsAsync() with parametersMOQ: 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核心的xUnit环境Moq 4.6.36-alpha

谢谢你的帮助。

+0

它不应该仅仅是:'Task.FromResult (新StoreResult {实体= E})' –

+0

@CallumLinington - 随着'.Returns(Task.FromResult (新StoreResult {实体= E}));' e没有定义。 –

+1

这就是'It.IsAny'。给它一个适当的实体! –

回答

6

由于从卡勒姆Linigton我来下面溶液中的提示:

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

的关键区别是指定为了避免模棱两可的呼叫为lambda表达式的输入参数的类型。

相关问题