views:

76

answers:

1

In a test method (for a Fluent NHibernate mapping, although that's not really relevant) I have the following code wrapped in a bunch of usings and try/catch blocks:

new PersistenceSpecification<Entry>(session)
    .CheckProperty(e => e.Id, "1")
    .VerifyTheMappings();

I would like to refactor this so that I can pass it to a helper method (where I place the using and try/catch blocks).

My requirements for this to work as I want it to are

  1. session needs to be provided by one of the using statements
  2. Entry should be provided as a generic parameter, so I can test mappings of various objects
  3. It should be possible to replace .CheckProperty(e => e.Id, "1").VerifyTheMappings() with anything that's called on a PersistenceSpecification<T> when defining the argument (in the test method).

Basically, I'd like to do something like this:

var testAction = new PersistenceSpecification<Entry>(session)
                      .CheckProperty(e => e.Id, "1")
                      .VerifyTheMappings();

HelpTestMethod(testAction)

but with the above requirements satisified.

+2  A: 

What about something like:

Action<PersistenceSpecification<Entry>> testAction = pspec => pspec
                .CheckProperty(e => e.Id, "1")
                .VerifyTheMappings();

HelpTestMethod<Entry>(testAction);

public void HelpTestMethod<T>(Action<PersistenceSpecification<T>> testAction)
{
    using(var session = new SessionFactory().CreateSession(...))
    {
        testAction(new PersistenceSpecification<T>( session ));
    }
}
LBushkin
Thanks! I had to modify the code slightly - for example, I couln't assign a lambda to an anonymously typed variable - but now it works like a charm! I'll edit your post within minutes to reflect the changes I had to make, so the next guy that finds this can benefit even more from it =)
Tomas Lycken