Unlike the pattern illustrated by Ayende or that I added onto here, I wanted NHibernate's SessionFactory and Session objects to return data that I could not return from the database because of unique index constraints.
In this scenerio I'm returning data from the database that matches certain values and it should always return a list that contains either 0 or 1 objects otherwise it throws an exception:
Problem is that integration tests are unlikely to uncover this error with normal data and end user testing won't uncover it either. This is simple, but I want to make certain that the exception is correctly thrown.
The only tricky part really is that after mocking the ISessionFactory & ISession objects you need to also mock each ICriteria object returned from the Session object. So with Rhino Mocks after telling it to expect a call to CreateCriteria that returns an ICriteria, we also need to create expectations for this result calling Add and its result calling list. This is because fluent interfaces use method chaining which makes this part a little tedious:
This allows us to now test what would actually happen if more than one Animal objects were returned. NHibernate makes this easy because there are interfaces for pretty much every object.
FYI: this code uses Rhino Mocks, NBuilder, NUnit & NHibernate
1 comment:
Scott White's blog post, "Unit Testing - Mocking to Test Edge Cases with NHibernate," offers a practical exploration of how mocking can be employed to test scenarios that are otherwise difficult to replicate with real data due to database constraints. By utilizing tools like Rhino Mocks, NBuilder, and NUnit, White demonstrates how to simulate conditions—such as multiple records returned when only one is expected—that are challenging to produce in a live database environment. This approach underscores the value of mocking in unit testing, particularly for verifying that exceptions are correctly thrown in edge cases. However, it's important to note that over-reliance on mocking can lead to tests that are tightly coupled to the implementation, potentially increasing maintenance overhead during refactoring . Therefore, while mocking is a powerful tool for testing edge cases, it should be used judiciously to maintain test robustness and reliability.
________________
Experienced in plumbing repairs – happy to help with questions about polybutylene fittings!
Post a Comment