【问题标题】:How to mock a generic Get method when using Ninject and use a SetUp method to populate the mocked database?使用 Ninject 时如何模拟通用 Get 方法并使用 SetUp 方法填充模拟数据库?
【发布时间】:2018-05-10 18:47:42
【问题描述】:

我的解决方案中使用了NinjectMoq。我使用实体框架,并使用 FakeDbSet 实现(见下文)。这让我可以使用GetByIdCreateUpdate 和其他方法来工作,因为我实现了它们的方式。

我所有的服务都有一个方法,例如:

List<Invoice> GetBySpecification(InvoiceSpecification specification);

这是唯一一个我不能轻易模拟的,因为我的实现是这样的,我使用DbContext 并使用Where 语句。

 public int GetBySpecification(InvoiceSpecification specification)
        {
            IQueryable<Invoice> query = BuildQuery(specification);
            return query.Count();
        }

        public IQueryable<Invoice> BuildQuery(InvoiceSpecification specification)
        {
            IQueryable<Creditor> query = _db.Creditors;

            if (!string.IsNullOrWhiteSpace(specification.Query))
            {
                var search = specification.Query.ToLower().Trim();
                query = query.Where(c => c.OfficeEmail.Contains(search)
                    || c.OfficePhone.Contains(search)
                    || c.CompanyRegistrationNumber.Contains(search)
                    || c.CompanyName.Contains(search)
                    || c.LastName.Contains(search)
                    || c.FirstName.Contains(search));
            }
            if (!string.IsNullOrWhiteSpace(specification.CompanyRegistrationNumber))
            {
                var search = specification.CompanyRegistrationNumber.ToLower().Trim();
                query = query.Where(c => c.CompanyRegistrationNumber == search);
            }
            if (specification.UpdateFrequency.HasValue)
            {
                query = query.Where(c => c.UpdateFrequency == specification.UpdateFrequency.Value);
            }

            return query.Where(c => !c.DateDeleted.HasValue);
        }

我的问题:

我希望在上课时能够使用SetUp。我想测试我的GetBySpecificationBuildQuery 方法,在其他方法中使用这些方法并不少见。

我希望能够运行 SetUp 方法,使用填充到列表中的 C# 对象在内存中提供一些“基本数据库”,因此当我使用 _db.Creditors 时,它会返回一个自定义的债权人列表设置,然后使用该查询。

我想我还很远,但不完全确定我从这里如何继续。我想我需要以某种方式更新我的 Resolver / FakeDb 集,但我非常感谢有人能在正确的方向上帮助我。

我的 Ninject 解析器:

    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<ILikvidoWebsitesApiContext>().ToProvider(new MoqContextProvider());
        // other awesome stuff
    }

我的 MoqContextProvider:

 public class MoqContextProvider : Provider<ILikvidoWebsitesApiContext>
    {
        protected override ILikvidoWebsitesApiContext CreateInstance(IContext context)
        {
            var mock = new Mock<ILikvidoWebsitesApiContext>();

            mock.Setup(m => m.Creditors).Returns(new FakeDbSet<Creditor>());
            return mock.Object;
        }
    }

FakeDbSet 实施:

public class FakeDbSet<T> : DbSet<T>, IDbSet<T> where T : class
{
    List<T> _data;

    public FakeDbSet()
    {
        _data = new List<T>();
    }

    public override T Find(params object[] keyValues)
    {
        var keyProperty = typeof(T).GetProperty(
            "Id",
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
        var result = this.SingleOrDefault(obj =>
            keyProperty.GetValue(obj).ToString() == keyValues.First().ToString());
        return result;
    }

    public override T Add(T item)
    {
        _data.Add(item);

        // Identity incrementation flow
        var prop = item.GetType().GetProperty("Id", typeof(int));
        if (prop != null)
        {
            var value = (int)prop.GetValue(item);
            if (value == 0)
            {
                prop.SetValue(item, _data.Max(d => (int)prop.GetValue(d)) + 1);
            }
        }
        return item;
    }

    public override T Remove(T item)
    {
        _data.Remove(item);
        return item;
    }

    public override T Attach(T item)
    {
        return null;
    }

    public T Detach(T item)
    {
        _data.Remove(item);
        return item;
    }

    public override T Create()
    {
        return Activator.CreateInstance<T>();
    }

    public new TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class, T
    {
        return Activator.CreateInstance<TDerivedEntity>();
    }

    public new List<T> Local
    {
        get { return _data; }
    }

    public override IEnumerable<T> AddRange(IEnumerable<T> entities)
    {
        _data.AddRange(entities);
        return _data;
    }

    public override IEnumerable<T> RemoveRange(IEnumerable<T> entities)
    {
        for (int i = entities.Count() - 1; i >= 0; i--)
        {
            T entity = entities.ElementAt(i);
            if (_data.Contains(entity))
            {
                Remove(entity);
            }
        }

        return this;
    }

    Type IQueryable.ElementType
    {
        get { return _data.AsQueryable().ElementType; }
    }

    Expression IQueryable.Expression
    {
        get { return _data.AsQueryable().Expression; }
    }

    IQueryProvider IQueryable.Provider
    {
        get { return _data.AsQueryable().Provider; }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _data.GetEnumerator();
    }

    IEnumerator<T> IEnumerable<T>.GetEnumerator()
    {
        return _data.GetEnumerator();
    }
}

【问题讨论】:

  • stackoverflow.com/questions/5609508/… 可能会有所帮助。单元测试 EF 有时收益递减,集成测试可能更有帮助。
  • @ATerry 如果您只是在测试 EF,我不反对,但我确实有很多不错的逻辑要在这里测试。 “真正”的解决方案可能是实现适当的存储库,但在这个阶段我想避免它(这么多额外的代码):-)
  • 有一些非常不错的框架可以实现通用 repos。这将大大减少您编写的额外代码。我在过去的生活中使用过这个github.com/urfnet/URF.NET。不过,它只有一个 EF 提供者。 github 上还有其他一些提供者,如 mongo、casandra 等。
  • 您将需要设置/模拟 DbSet 的 IQueryable 实例,正如 MSDN article 所解释和详细说明的那样。有两种类型,一种用于标准查询,另一种用于异步查询。恕我直言,建立一个单元/集成测试数据库和该数据库的种子/设置数据比模拟 EF 更容易。

标签: c# asp.net asp.net-mvc moq ninject


【解决方案1】:

我不明白为什么 EntityFramework 甚至会参与此方法的单元测试。

C#中的注入分为三种:

  1. 构造函数注入
  2. 方法注入
  3. 属性注入

如果你注入 IQueryable,那么你将把这个方法从实体框架中解耦。您的逻辑现在无需模拟 EF 即可测试。

让你的第一个方法这样做:

    public int GetBySpecification(InvoiceSpecification specification)
    {
        IQueryable<Invoice> query = BuildQuery(specification, _db.Creditors);
        return query.Count();
    }

您的第二种方法现在允许注入可查询对象。您不再需要 EF 参与逻辑测试。

    public IQueryable<Invoice> BuildQuery(InvoiceSpecification specification, IQueryable<Creditor> query)
    {
        if (!string.IsNullOrWhiteSpace(specification.Query))
        {
            var search = specification.Query.ToLower().Trim();
            query = query.Where(c => c.OfficeEmail.Contains(search)
                || c.OfficePhone.Contains(search)
                || c.CompanyRegistrationNumber.Contains(search)
                || c.CompanyName.Contains(search)
                || c.LastName.Contains(search)
                || c.FirstName.Contains(search));
        }
        if (!string.IsNullOrWhiteSpace(specification.CompanyRegistrationNumber))
        {
            var search = specification.CompanyRegistrationNumber.ToLower().Trim();
            query = query.Where(c => c.CompanyRegistrationNumber == search);
        }
        if (specification.UpdateFrequency.HasValue)
        {
            query = query.Where(c => c.UpdateFrequency == specification.UpdateFrequency.Value);
        }

        return query.Where(c => !c.DateDeleted.HasValue);
    }

试试看。

另一个重构想法。 . . 更好的办法是将 QueryBuilder 移到它自己的对象中。

 public interface IInvoiceSpecificationQueryBuilder
 {
     IQueryable<Invoice> BuildQuery(InvoiceSpecification specification, IQueryable<Creditor> query)
 }

 public class InvoiceSpecificationQueryBuilder : IInvoiceSpecificationQueryBuilder
 {
     public IQueryable<Invoice> BuildQuery(InvoiceSpecification specification, IQueryable<Creditor> query)
     {
        // method logic here
     }
 }

现在您可以使用三种注入类型中的任何一种将 IInvoiceSpecificationQueryBuilder 注入到承载 GetBySpecification() 方法的类中。

为了测试 GetBySpecification,您只需要测试是否使用正确的参数调用了 BuildQuery。

模拟 EF(不理想但仍然是一种选择)

如果您对模拟实体框架一无所知,那么 bm7716 给了您一篇不错的文章。我在这里实现了该文章中代码的通用实现:https://www.rhyous.com/2015/04/10/how-to-mock-an-entity-framework-dbcontext-and-its-dbset-properties。欢迎您尝试一下。 Moq 的更高版本存在错误,因此请返回 Moq 4.7 以避免它。

更好的选择是将 EF 从您的逻辑中移除/解耦。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2020-12-08
    • 1970-01-01
    相关资源
    最近更新 更多