Delegates For LLBLGen Entities

Wednesday, July 15 2009

This isn’t meant to be an LLBLGen-centric blog; I just work with it a lot and happen to come across a lot of these little nuances.

When writing unit tests, I make every effort to mock or fake all dependencies on the code that I’m testing. When it comes to testing repositories, it usually requires mocking of LLBLGen’s classes so that I do not end up talking to the database during the unit tests. In this case, I want to mock the LLBLGen method FetchEntity(IEntity2 entityToFetch), which populates entityToFetch via reference and returns whether or not the fetch was successful in terms of a boolean. In order to thoroughly test a method using FetchEntity, I need to return fake data. To do that, I create a delegate method:

   1: private IEntity2 _entityToFetch;
   2: private delegate bool FetchEntityDelegate(IEntity2 entity);
   3: private bool FetchEntity(IEntity2 entity)
   4: {
   5:     if (_entityToFetch != null)
   6:     {
   7:         entity = _entityToFetch;
   8:     }
   9:     return true;
  10: }

 

When I want to use this delegate, I set _entityToFetch to the entity that I want returned and call the delegate, right? It’s not that easy, unfortunately. On line 7 above, entity is merely being set to a reference to _entityToFetch, which is not passed along once this delegate is finished executing. The calling method still gets an empty entity.

What do we do here? Well, in actuality I am really only interested in the fields of this entity. If I can get the fields to be copied over to the entity, we’re golden. This is accomplished using Clone():

   1: entity.Fields = _entityToFetch.Fields.Clone();

This will copy over the fields from _entityToFetch to entity and successfully returns them to the calling function. Now I can easily get fake data from FetchEntity and test methods using it to my heart’s content.

Comments

Brendan Enrick said on 7.15.2009 at 9:14 AM

Nice post. I recommend turning off the line numbers for your code snippet plug-in. The numbers will make it difficult for people to copy and paste since they will get line numbers copied as well.


sdepouw said on 7.15.2009 at 9:19 AM

Glad you liked it. Thanks for the tip!