views:

94

answers:

1

I'm new to NHibernate (+Fluent), and I can't decide on what's the best strategy when it comes to structuring my code to make it testable. I have a plain structure including a domain model, mappings to map the model to database, and a few classes with behavior which will work towards the model classes and do transactions for updating and reading out data from the database. I have more on top of this, but that's not relevant here.

Now, when it comes to the unit testing what seems natural to me is to inject something to the behavior classes such that they will get a SQLite database for testing, or the real database however this is configured. Does this make sense? What I can't decide is what to inject.

  • I could inject the ISession, but I assume I'd want to use new sessions for each - well - session? If so I'd need something outside to create the sessions, which might just move the problem?
  • Could I inject the SessionSource? In this case the behavior classes could create sessions themselves using this. However, I see the SessionSource is used to BuildSchema - something I assume I only want to do once?
  • The third option I see - and what I've done this far - is to create a SessionFactory which creates a session for me. Using this I can add a using-clause and have the session disposed when the function finishes. I have a SessionFactory-interface and a regular and a unittest implementation. Injecting either the regular or unittest implementation I get a session for the right database.

Am I on the right track? How should I strcuture my code for writing unit tests for code using NHibernate? Any best practices I should be aware of?

+4  A: 

You may want to check out this blog post by Ayende: Nhibernate Unit Testing. He has a test base class that configures the session with an in memory database (sql lite). This seems be similar to your third option.

Daniel Auger