2017-03-24 2 views
1

Ich bin mit der spöttischen Bibliothek Moq und ich bin nicht in der Lage ein Modell für diese Signatur-Setup:Cant Setup Mock mit moq für generische IEnumerable Aufgabe

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; 
} 

Unit-Test-Klasse

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>()); 

      } 
     } 
    } 
} 

Diese Codezeile wird mich verrückt:

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

Das Problem ist, ich tun nicht wissen, wie man GetAllAsync einrichtet, also kompiliert es und dass es eine Liste der Produkte zurückbringt. Das gewünschte Verhalten, dass es eine Liste von Produkten zurückgibt.

Kann mir jemand bei der Einrichtung des Mocks mit dieser Signatur helfen?

Antwort

3

Zunächst stellte das anfängliche Beispiel hat die orderBy Parameter als

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

Aber im Setup gibt es

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

die pflegt die Definition der Schnittstelle entspricht und einen Übersetzungsfehler verursachen.

Zweitens, verwenden Sie für die optionalen Parameter, um die gespiegelte Methode flexibel zu sein, wenn Sie den Test durchführen.

Das folgende einfache Beispiel zeigt

[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()); 
}