views:

99

answers:

1

I have a many to many relationship between A and B. (I know I can consider refactoring etc, but that's another matter). my Code does something like this:

// given aId is the Id of an instance of A, and A has a many to many set of B's
    A a = myActiveSession.Get<A>(aId);
    a.Bs.Add(new B() {Name="dave"});

and I get an exception because a.Bs is NULL. this only happens in the context of a test suite, and when I run the single test I get a set and everything is ok. I expect that since the default is lazy fetch, Bs will be initialized when I access the property getter, but if this fails I expect to get an exception, and not simply null... since this way I have no immediate clue what caused this. any ideas?

PS: this is the mapping:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
namespace="MyNamespace" assembly="MyAssembly">
  <class name="A" table="A" dynamic-update="true">
    <id name="id" type="integer" access="field">
      <column name="ID"/>
      <generator class="native"/>
    </id>
    <property name="name" type="string" access="field"/>
    <set name="Bs" table="A_B">
      <key column="a_id"/>
      <many-to-many column="b_id" class="B" />
    </set>
  </class>
</hibernate-mapping>


UPDATE: I've managed to get this to work when I fixed some code that did session cleanup (see @Darin Dimitrov's suggestion), however, I still don't understand what could have caused this strange behavior (instead of receiving some clear exception). so at the moment this remains a mystery.

+1  A: 

Unit tests could execute in parallel from different threads and for this reason they should be independent. I suspect that in your case the Session object is reused in multiple tests and one another test could messes up with Bs property. Make sure the session is created inside your test and is destroyed afterwards i.e.

using (var session = sessionFactory.OpenSession())
{
    A a = myActiveSession.Get<A>(aId);
}
Darin Dimitrov
I would suspect that too, but in this case I am sure that the tests aren't run in parallel.
Yonatan Karni
Even if they are not run in parallel stale objects could stay in the session from a previous test run. That's why it is a good practice to create a new session for each test.
Darin Dimitrov
that's true, but I do create a new session. I'm also making changes in our session factory (trying to move from a session pool to using NHibernate's session pool and relying on ADO.net connection pooling) so I'm looking into that as well. but I'm wondering what could cause this, because even if there's a problem with my session, the A instance is created in a separate earlier step of the same test (and committed), and is later fetched. when could the association, which comprises of two new objects, have gone bad?
Yonatan Karni