2015-09-18 27 views
2

我真的很努力地完成這項工作。我有一個通用的存儲庫模式,我需要使用Microsoft Fakes存根存儲庫接口。存根接口與帶謂詞的泛型方法

public interface IDataAccess<T> where T : class 
{ 
    void Add(T entity); 
    void Update(T entity); 
    void Delete(T entity); 
    void Delete(Expression<Func<T, bool>> where); 
    T FindById(long id); 
    T FindById(string id); 
    T Find(Expression<Func<T, bool>> where); 
    IEnumerable<T> FindAll(); 
    IEnumerable<T> FindMany(Expression<Func<T, bool>> where); 
    IQueryable<T> Find(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes); 
    IQueryable<T> FindIncluding(params Expression<Func<T, object>>[] includeProperties); 
} 

試圖創建一個存根

IQueryable<T> Find(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes); 
IQueryable<T> FindIncluding(params Expression<Func<T, object>>[] includeProperties); 

,並在我的測試..

IDataAccess<EnterprisePermissionSet> dataAccess = new HG.Fus.Authentication.Data.Fakes. 
      StubIDataAccess<EnterprisePermissionSet>() 
     { 
      FindIncludingExpressionOfFuncOfT0ObjectArray =() => { }; 
     }; 

我只是不知道如何構建這個存根,

+0

你要模仿你在裏面尋找的行爲'{}' –

+0

這是我在做什麼,但是也會不斷收到錯誤,我無法將源類型'Lambda表達式'轉換爲目標類型'IQueryable ' – JBeckton

+0

好吧,閱讀我的答案,我將展示如何對這些方法進行存根... –

回答

0

MsFakes用途代碼生成替換爲假方法,創建存根等... To r您必須設置一個特殊方法來設置新方法(基於方法簽名的ActionFunc),該方法將接收對此特定方法的任何調用。

要假方法的簽名是:

IQueryable<T> FindIncluding(params Expression<Func<T, object>>[] includeProperties); 

在此基礎上簽名,你必須設置一個Func它獲取的Expression<Func<T, object>>數組並返回IQueryable<T>。 如下片段展示一個簡單的例子來代替上述方法:

fakeDataAccess.FindIncludingExpressionOfFuncOfT0ObjectArray = expressions => 
{ 
    // here you can create the logic/fill the return value and etc... 
    return new List<EnterprisePermissionSet>().AsQueryable(); \\this example is match your T 
}; 

模擬IQueryable<T>最簡單的方法是通過AsQueryable()返回一個集合,另一種方式是使用EnumerableQuery類。

這裏的例子來代替:IQueryable<T> Find(Expression<Func<T, bool>> predicate = null, params Expression<Func<T, object>>[] includes);

fakeDataAccess.FindExpressionOfFuncOfT0BooleanExpressionOfFuncOfT0ObjectArray = 
(expression, expressions) => 
    { 
      // here you can create the logic/fill the return value and etc... 
      return new List<EnterprisePermissionSet>().AsQueryable(); 
    };