2017-03-24 27 views
1

我使用的嘲弄庫起訂量,我無法安裝這個簽名模擬:廣東話設置模擬與起訂量爲通用的IEnumerable任務

Task<IEnumerable<TEntity>> GetAllAsync<TEntity>(
      Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, 
      string includeProperties = null, 
      int? skip = null, 
      int? take = null) 
      where TEntity : class, IEntity; 
} 

的單元測試類

using System.Collections.Generic; 
using System.Linq; 
using System.Linq.Expressions; 
using System.Threading.Tasks; 
using ICEBookshop.API.Factories; 
using ICEBookshop.API.Interfaces; 
using ICEBookshop.API.Models; 
using Moq; 
using SpecsFor; 

namespace ICEBookshop.API.UnitTests.Factories 
{ 
    public class GivenCreatingListOfProducts : SpecsFor<ProductFactory> 
    { 
     private Mock<IGenericRepository> _genericRepositorMock; 

     protected override void Given() 
     { 
      _genericRepositorMock = new Mock<IGenericRepository>(); 
     } 

     public class GivenRepositoryHasDataAndListOfProductsExist : GivenCreatingListOfProducts 
     { 
      protected override void Given() 
      { 
       _genericRepositorMock.Setup(
         expr => expr.GetAllAsync<Product>(It.IsAny<Func<IQueryable<Product>>>(), null, null, null)) 
        .ReturnsAsync<Product>(new List<Product>()); 

      } 
     } 
    } 
} 

這行代碼是讓我瘋:

genericRepositorMock.Setup(
         expr => expr.GetAllAsync<Product>(It.IsAny<Func<IQueryable<Product>>>(), null, null, null)) 
        .ReturnsAsync<Product>(new List<Product>()); 

的問題是我做的不知道如何設置GetAllAsync,因此它會編譯並返回一個產品列表。它返回產品列表的期望行爲。

任何人都可以幫我設置這個簽名模擬?

回答

3

首先,最初提供的例子具有orderBy參數作爲

Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy 

但在設置有

It.IsAny<Func<IQueryable<Product>>>() 

其不會匹配接口的定義和引起編譯錯誤。

其次,使用It.IsAny<>作爲可選參數,以便在執行測試時使模擬方法更加靈活。

下面的簡單的示例演示

[TestMethod] 
public async Task DummyTest() { 
    //Arrange 
    var mock = new Mock<IGenericRepository>(); 
    var expected = new List<Product>() { new Product() }; 
    mock.Setup(_ => _.GetAllAsync<Product>(
     It.IsAny<Func<IQueryable<Product>, IOrderedQueryable<Product>>>(), 
     It.IsAny<string>(), 
     It.IsAny<int?>(), 
     It.IsAny<int?>() 
     )).ReturnsAsync(expected); 

    var repository = mock.Object; 

    //Act 
    var actual = await repository.GetAllAsync<Product>(); //<--optional parameters excluded 

    //Assert 
    CollectionAssert.AreEqual(expected, actual.ToList()); 
}