我正在玩.NET MVC,我正在编写一些单元测试。我有一个接口库,看起来像这样:如何使用Moq来模拟存储库Single(Expression <Func <TEntity,bool >> predicate)方法
public interface IRepository<TEntity> : IDisposable where TEntity : class
{
IQueryable<TEntity> GetAll();
TEntity Single(Expression<Func<TEntity, bool>> predicate);
}
我都嘲笑GETALL方法是这样的:
_mockRepository.Setup(x => x.GetAll()).Returns(
new List<Post>
{
new Post { Title = "Test Post 1" },
new Post { Title = "Test Post 2" }
}.AsQueryable());
现在,我不知道我怎么会嘲笑单一的方法,因为它有一个包含我想要评估的表达式的参数。
感谢,
B3N
编辑:
我改变了代码:
_mockRepository.Setup(x => x.Single(It.IsAny<Expression<Func<Post, bool>>>()))
.Returns((Expression<Func<Post, bool>> expr) => new List<Post> {
new Post { PostId = 1, Title = "Test Post 1", Created = DateTime.Now },
new Post { PostId = 2, Title = "Test Post 2", Created = DateTime.Now }
}.Where(expr));
但我现在收到以下错误:
“System.Collections中.Generic.List'不包含'Where'和最佳扩展名m的定义ethod重载'System.Linq.Queryable.Where(System.Linq.IQueryable,System.Linq.Expressions.Expression>)'有一些无效的参数。
这是甚至是最好的方法来做到这一点,或者应该单一的方法只返回一个新的职位,甚至没有考虑传递的表达式?
编辑2:
这是工作结果。
_mockRepository.Setup(x => x.Single(It.IsAny<Expression<Func<Post, bool>>>())).Returns(
(Expression<Func<Post, bool>> expr) =>
new List<Post>
{
new Post { PostId = 1, Title = "Test Post 1", Created = DateTime.Now },
new Post { PostId = 2, Title = "Test Post 2", Created = DateTime.Now }
}.Single(expr.Compile()));
伟大的问题...指出我在正确的方向。 – IbrarMumtaz 2012-05-28 09:40:30