Nsubstitute set return value with Generic Repository

Nsubstitute set return value with Generic Repository

我有一个 MongoDB 的通用存储库。

这是我的 Get 方法:

public IList<TEntity> Get<TEntity>(System.Linq.Expressions.Expression<Func<TEntity, bool>> filter = null) where TEntity : class, new()
{
    var collection = GetCollection<TEntity>();

    var query = Query<TEntity>.Where(filter);
    var entity = collection.FindAs<TEntity>(query).ToList();

    return entity;
}

当我尝试模拟它时,出现错误:

IList<Login>(其中 Login 是我的业务对象)不包含 ReturnsForAnyArgs.

的任何定义
[TestMethod]
public void CheckIfUserNameExits_IfUserNameDoesNotExist_ReturnFalse()
{
    Login login = null;
    Task<IList<Login>> logl = null;
    // _mongoDAL.Get<Arg.Any<Login>()>(Arg.Any<Expression<Func<TEntity, bool>>>).ReturnsForAnyArgs
    //_mongoDAL.When(x => x.Get<Login>(Arg.Any<Expression<Func<Login, bool>>>())).ReturnsForAnyArgs(logl);
    _mongoDAL.Get<Login>(Arg.Any<Expression<Func<Login, bool>>>()).ReturnsForAnyArgs(logl);
}

关于如何模拟它的任何建议,以便我可以在我的单元测试中设置我想要的 return 值?

解决了。

List<Login> loginList = new List<Login>()
            {
            };

     _mongoDAL.Get<Login>(Arg.Any<Expression<Func<Login, bool>>>()).Returns(loginList);

不知道为什么 Returns 就可以了。

问题是由于您向 ReturnsForAnyArgs 调用传递了错误的类型。如果您调用 ReturnsReturnsForAnyArgs.

,此行为是相同的

您的 Get 方法定义为返回 IList<TEntity>。在您最初的问题中,您将返回 logl,类型为 Task<IList<Login>>(请注意 Task 包裹着您的 IList)。但是,在您的 中,您传递的是 loginList,这是一个 List<T>,它实现了 IList<T>,因此您的代码可以编译。因此,作为替代方案,您可以使用:

_mongoDAL.Get<Login>(Arg.Any<Expression<Func<Login, bool>>>())
         .ReturnsForAnyArgs(loginList);

您最初得到的编译错误有点神秘。完整的错误信息是:

error CS1928: 'System.Collections.Generic.IList' does not contain a definition for 'ReturnsForAnyArgs' and the best extension method overload 'NSubstitute.SubstituteExtensions.ReturnsForAnyArgs(System.Threading.Tasks.Task, T, params T[])' has some invalid arguments

错误消息的前半部分看起来好像指向缺少的扩展方法。然而,实际上问题在于它无法匹配任何重载方法,因此它会选择最接近的方法并向您展示它如何不匹配。

通常您会收到第二个错误,这将有助于表明这是您的问题。像这样:

error CS1929: Instance argument: cannot convert from 'System.Collections.Generic.IList' to 'System.Threading.Tasks.Task>>'