Hibri Marzook Musings on technology and occsionally photography

Using NHibernate Profiler with database integration tests.

The NHibernate Profiler is a pretty cool tool. If you are using NHibernate and want to see how your application/website uses NHibernate this is what you need.

But, why wait till you use the whole application to start using the profiler. Why not use it when writing  writing tests , while building your mappings and when building your NHibernate queries. It’s really easy to do this.

First, get the NHibernate profiler from www.nhprof.com. Extract the contents to a location. From your test project, add a reference to HibernatingRhinos.NHibernate.Profiler.Appender.dll in the NHProf package.

This is my small test class.

[TestFixture]
    public class EpisodeTests : BaseTest
    {
        [SetUp]
        public override void SetUp()
        {
            base.SetUp();
            ActiveRecordStarter.Initialize(typeof(Episode).Assembly, new XmlConfigurationSource("activerecord.xml"));
        }

        [Test]
        public void CanPersistTitle()
        {
            Episode episode = new Episode();
            string expectedTitle = "Dr Who and the Daleks";
            episode.Title = expectedTitle;
            episode.Save();
           
            Guid savedEpisodeId = episode.Id;
            episode = ActiveRecordBase<Episode>.Find(savedEpisodeId);

            Assert.That(episode.Title, Is.EqualTo(expectedTitle));

        }
    }

</p>

 

</p>

I’m using Castle ActiveRecord (which uses NHibernate behind the scenes) to demonstrate this. To enable NHProf to profile the test, add a static constructor to the super class , BaseTest. In the static constructor, add the following code.

HibernatingRhinos.NHibernate.Profiler.Appender.NHibernateProfiler.Initialize();

Go to where you extracted NHProf and run the profiler exe. Run the test and watch the magic.

image

NHProf is now profiling your integration tests. You can leave this running in the background while you are working on the tests.

You get immediate feedback NHibernate best practice violations, and you can_ fix them while writing tests._ You don’t have to wait till deployment to profile your code. Although this doesn’t give the whole picture of how your application is using NHibernate , you still can fix many things early. I highly recommend running NHProf while running automated acceptance test scenarios.

Technorati Tags: ,

 

By Hibri Marzook

Discuss this post with me on @hibri