Thursday 15 January 2015

Verifying interaction with 3rd-party frameworks via tests - NHibernate

Following on from my previous post regarding tests that verify how code interacts with Castle Windsor, this post looks at the same concept with NHibernate.

One of my classes works with NHibernate sessions, opening and disposing them. As with releasing components using Castle Windsor, ensuring that sessions are disposed is essential.

The NHibernate SessionFactory contains a Statistics property that provides access to many useful metrics. Including this parameter in the NHibernate config <property name="generate_statistics">true</propertyenables the ability to inspect these statistics.

Now, using the Statistics class, the test becomes quite simple:

<Test()>
<Category(TestCategory.Integration)>
Public Sub Execute_NoSessionInjected_ShouldCreateAndDisposeItsOwnSession()
 
   Dim expectedSessionCloseCount = SessionProvider.Factory.Statistics.SessionCloseCount + 1
 
   _controller.Execute(Of ICommand)()
 
   Assert.That(expectedSessionCloseCount, [Is].EqualTo(SessionProvider.Factory.Statistics.SessionCloseCount))
 
End Sub
The test gets the current count of sessions closed and increments it, as we're expecting it to. It does the test action and then asserts using the Statistics property that NHibernate has closed one more session than it had before we acted.

Inspecting the SessionFactory statistics is also useful for testing second-level caching.

No comments:

Post a Comment