2016-02-13 24 views
1

我有一個MongoDB的通用存儲庫。Nsubstitute設置通用存儲庫的返回值

這是我的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>(其中登錄名是我的業務對象)不包含任何對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); 
} 

關於如何模擬它的任何建議,以便我可以在我的單元測試中設置我想要的返回值?

+0

「......不包含任何對ReturnsForAnyArgs定義」 - 這聽起來像是你缺少一個'使用NSubstitute;'? –

+0

是的,我已經包括它。 :) – Strawberry

回答

0

該問題是由於您將錯誤的類型傳遞給ReturnsForAnyArgs調用引起的。如果您致電ReturnsReturnsForAnyArgs,則此行爲是相同的。您的Get方法定義爲返回IList<TEntity>。在您的第一個問題中,您將返回logl,這是Task<IList<Login>>(注意Task包裝您的IList)。然而,在你的solution中,你是通過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>>'

1

解決了它。

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

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

不知道爲什麼只有返回,它的工作原理。