views:

47

answers:

1

Hi Guys,

I'm attempting to test my repository using an in-memory mock context.

I implement this with an in-memory Dictionary, as most people do. This implements members on my repository interface to Add, Remove, Find, etc, working with the in-memory collection.

This works fine in most scenarios:

[TestMethod]
public void CanAddPost()
{
    IRepository<Post> repo = new MockRepository<Post>();
    repo.Add(new Post { Title = "foo" });
    var postJustAdded = repo.Find(t => t.Title == "foo").SingleOrDefault();
    Assert.IsNotNull(postJustAdded); // passes
}

However, i have the following test which i cannot get to pass with the mock repository (works fine for the SQL repository).

Consider i have three repositories:

  1. Posts (handles user content posts, like a StackOverflow question).
  2. Locations (locations in the world, like "Los Angeles").
  3. LocationPosts (junction table to handle many-many between Posts/Locations).

Posts can be added to nowhere, or they can also be added with a particular Location.

Now, here's my test:

[TestMethod]
public void CanAddPostToLocation()
{
   var location = locationRepository.FindSingle(1); // Get LA
   var post = new Post { Title = "foo", Location = location }; // Create post, with LA as Location.
   postRepository.Add(post); // Add Post to repository

   var allPostsForLocation = locationPostRepository.FindAll(1); // Get all LA posts.
   Assert.IsTrue(allPostsForLocation.Contains(post)); // works for EF, fails for Mock.
}

Basically, when using the "real" EF/SQL Repository, when i add a Post to a particular location, EntityFramework is smart enough to add the "LocationPost" record, because of the association in the EDMX ("LocationPosts" navigational property on "Post" entity)

But how can i make my Mock repository smart enough to "mimic" this EF intelligence?

When i do "Add" on my mock repository, this just adds to the Dictionary. It has no smarts to go "Oh, wait, you have a dependant association, let me add that to the OTHER repository for you".

My Mock Repository is generic, so i dont know how to put the smarts in there.

I have also looked at creating a FakeObjectContext / FakeObjectSet (as advised by Julie Lerman on her blog), but this still does not cover this scenario.

I have a feeling my mocking solution isn't good enough. Can anyone help, or provide an up-to-date article on how to properly mock an Entity Framework 4/SQL Server repository covering my scenario?

The core of the issue is i have one repository per aggregate root (which is fine, but is also my downfall).

So Post and Location are both aggregate roots, but neither "own" the LocationPosts.

Therefore they are 3 seperate repositories, and in an in-memory scenario, they are 3 seperate Dictionaries. I think i'm missing the "glue" between them in my in-memory repo.

EDIT

Part of the problem is that i am using Pure POCO's (no EF code generation). I also do not have any change tracking (no snapshot-based tracking, no proxy classes).

I am under the impression this is where the "smarts" happen.

At the moment, i am exploring a delegate option. I am exposing a event in my Generic Mock Repository (void, accepts generic T, being the Entity) which i invoke after "Add". I then subscribe to this event in my "Post Repository", where i plan to add the related entities to the other repositories.

This should work. Will put as answer if it does so.

However, im not sure it this is the best solution, but then again, this is only to satisfy mocking (code won't be used for real functionality).

A: 

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.

RPM1984