Persistence specification testing combined with AutoFixture

March 13, 2011 | Unit Testing | NHibernate

When working with NHibernate you need to make sure that your mappings are correct. At least, you have to make sure that when you save an item you can also qet that item back.

If you are using FluentNHibernate you can use the PersistenceSpecification<T> class. However, the PersistenceSpecification<T> class requires that you pass the property to check and also a value for that property.

By using AutoFixture you can easily create objects that you can pass inside the CheckXx methods:

[Fact]
public void ShouldVerifyTheMappings()
{
    var fixture = new Fixture();

    using (session)
    {
        new PersistenceSpecification<EventType>(session)
            .CheckProperty(x => x.EventTypeId, 
                fixture.CreateAnonymous<long>())
            .CheckProperty(x => x.EventTypeName, 
                fixture.CreateAnonymous<string>())
            .CheckProperty(x => x.ExchangeServerId, 
                fixture.CreateAnonymous<int>())
            .CheckProperty(x => x.LastUpdatedOn, 
                DateTime.Today)
            .CheckProperty(x => x.NextMarketId, 
                fixture.CreateAnonymous<long>())
            .CheckReference(x => x.Bookmaker, 
                fixture.CreateAnonymous<Bookmaker>())
            .VerifyTheMappings();
    }
}

Combining AutoFixture with the PersistenceSpecification<T> class results in writing less code when testing NHibernate mappings, specially when dealing with complex types.