I am trying to mock out my Repository with Moq. I am trying to mock out all the query methods开发者_如何学C on my Repository. I have been successful in mocking out the method to return all of for the type I have mocked out.
Example:
mockProductRepo.Setup(x => x.GetAll()).Returns(products.AsQueryable());
However, I am having a problem mocking out a method that utilizes another method. For example, my "FilterBy" method returns a call to my "GetAll" method with a Where Clause that takes an expression
Example: Repository Method
public virtual IQueryable<T> FilterBy(Expression<Func<T, bool>> expression)
{
return GetAll().Where(expression);
}
The kicker is that I was hoping to mock out all the methods on the repository in a helper class:
public static IRepository<Product> MockProductRepository(params Product[] products) {
var mockProductRepo = new Mock<IRepository<Product>>();
mockProductRepo.Setup(x => x.GetAll()).Returns(products.AsQueryable());
mockProductRepo.Setup(x => x.FilterBy(It.IsAny<Expression<Func<Product, bool>>>())).Returns(products.AsQueryable().Where(It.IsAny<Expression<Func<Product, bool>>>()));
return mockProductRepo.Object;
}
So instead of the FilterBy method mocked out above, is there a way to set it up to call on another mocked out method instead of the way I have it in the above example?
UPDATE
I have tried the setup:
mockProductRepo.Setup(x => x.FilterBy(It.IsAny<Expression<Func<Product, bool>>>())).Returns(mockProductRepo.Object.GetAll().Where(It.IsAny<Expression<Func<Product, bool>>>()));
And it always errors that "Value cannot be null. Parameter: predicate". From what I understand of the stack trace it is complaining because I am not passing "Where" a predicate. I am not sure how in the setup to denote the expression passed into the FilterBy method to be used in the filter Where.
I figured it myself.
mockProductRepo.Setup(x => x.FilterBy(It.IsAny<Expression<Func<Product, bool>>>())).Returns((Expression<Func<Product,bool>> filter) => mockProductRepo.Object.GetAll().Where(filter));
精彩评论