How Do I Mock Entity Framework's Navigational Property Intelligence?

偶尔善良 提交于 2019-12-03 08:44:47

As i said in my EDIT, i explored the delegate option, which has worked succesfully.

Here's how i did it:

namespace xxxx.Common.Repositories.InMemory // note how this is an 'in-memory' repo
{
   public class GenericRepository<T> : IDisposable, IRepository<T> where T : class
   {
      public delegate void UpdateComplexAssociationsHandler<T>(T entity);
      public event UpdateComplexAssociationsHandler<T> UpdateComplexAssociations;

      // ... snip heaps of code

      public void Add(T entity) // method defined in IRepository<T> interface
      {
         InMemoryPersistence<T>().Add(entity); // basically a List<T>
         OnAdd(entity); // fire event
      }

      public void OnAdd(T entity)
      {
         if (UpdateComplexAssociations != null) // if there are any subscribers...
            UpdateComplexAssociations(entity); // call the event, passing through T
      }
   }
}

Then, in my In Memory "Post Repository" (which inherits from the above class).

public class PostRepository : GenericRepository<Post>
{
   public PostRepository(IUnitOfWork uow) : base(uow)
   {
      UpdateComplexAssociations += 
                  new UpdateComplexAssociationsHandler<Post>(UpdateLocationPostRepository);
   }

   public UpdateLocationPostRepository(Post post)
   {
      // do some stuff to interrogate the post, then add to LocationPost.
   }
}

You may also think "hold on, PostRepository derives from GenericRepository, so why are you using delegates, why don't you override the Add?" And the answer is the "Add" method is an interface implementation of IRepository - and therefore cannot be virtual.

As i said, not the best solution - but this is a mocking scenario (and a good case for delegates). I am under the impression not a lot of people are going "this far" in terms of mocking, pure POCO's and repository/unit of work patterns (with no change tracking on POCO's).

Hope this helps someone else out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!