Announcement Announcement Module
Collapse
No announcement yet.
unit testing Entity collections Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • unit testing Entity collections

    I have an application where I use local transaction management to control all persist/merge operations on my various entities. For query methods I don't use any transactions (believe this would be redundant).
    I have one main entity(let's call it Foo) which contains a collection of some other entities (lets say Bar). So the Foo object would get created and persisted using the usual
    Code:
    entityManager.persist(Foo);
    To associate a new Bar object with the Foo object I would first run an HQL query to find the correct Foo object (without using any transaction), call
    Code:
    foo.addBar(Bar);
    and then pass the Foo object onto a seperate method where I start a new transaction and call
    Code:
    entityManager.merge(Foo);
    In my production code this all works fine and the associations are maintained and appear in my database.
    My problem is in my unit tests (to be more accurate I guess they are more like integration tests) where I want to test that the addition of Bar objects to the collection do get persisted to the database correctly. Running using the SpringJUnit4ClassRunner I have a test that looks like so:

    Code:
    @Test
      public void testModelCollectionAddition()  {
        persistenceManager.addBar(bar);
        Foo other = persistenceManager.findCurrentFoo(fooId);
        assertEquals(1, other.getBarCollection().size());
      }
    The bar parameter is a mock object, the fooId a unique key for that mock object and the persistenceManager is the class that holds all my various persistence related methods.
    My assertion always fails as the returned "other" has an empty collection (even though I explicitly call getBarCollection.size() before returning the object in the findCurrentFoo method).
    So I'm confused as to how this works in production code but not in testing - can anyone shed any light on this?
Working...
X