c# - 具有采用谓词的通用方法的 stub 接口(interface)

标签 c# lambda microsoft-fakes

我真的很难让它发挥作用。我有一个通用存储库模式,我需要使用 Microsoft Fakes stub 存储库接口(interface)。

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

尝试为

创建 stub
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 = () => { };
        };

我只是不知道如何构建这个 stub ,

最佳答案

MsFakes使用代码生成来替换伪造的方法,创建 stub 等... 要替换特定方法,您必须设置新方法(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();
     };

关于c# - 具有采用谓词的通用方法的 stub 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32661180/

相关文章:

c# - 测试因 ShimNotSupportedException 而失败

c# - PCL 库可以与 ASP.NET MVC 一起运行吗?

c# - UserControl 中的数据绑定(bind)在设计时不起作用?

c# - Windows Mobile 'OK' 按钮

c# - 如何重定向到另一个页面并在该页面上触发事件?

lambda - 新的 lambda 语法是什么?

python - 带有嵌套列表的列表理解中的条件语句(Python 3) :

c# - 如何模拟/覆盖单元测试的只读字段

Jinja2 中的 Python lambda

.net - Microsoft Fakes 和 .Net 4.0