我正在玩.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