views:

536

answers:

1

I'm trying to set up integration tests using the AbstractTransactionalJUnit4SpringContextTests base class. My goal is really simple: insert some data into the database using the simpleJdbcTemplate, read it back out using a DAO, and roll everything back. JPA->Hibernate is the persistence layer.

For my tests, I've created a version of the database that has no foreign keys. This should speed up testing by reducing the amount of fixture setup for each test; at this stage I'm not interested in testing the DB integrity, just the business logic in my HQL.

/* DAO */

@Transactional
@Repository("gearDao")
public class GearDaoImpl implements GearDao {
    @PersistenceContext
    private EntityManager entityManager;

    /* Properties go here */

    public Gear findById(Long id) {
        return entityManager.find(Gear.class, id);
    }
}

/* Test Page */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/com/dom/app/dao/DaoTests-context.xml"})
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
public class GearDaoImplTests extends AbstractTransactionalJUnit4SpringContextTests   {

    @Autowired
    private GearDao gearDao;

    @Test
    @Rollback(true)
    public void quickTest() {
        String sql;
        // fields renamed to protect the innocent :-)
        sql = "INSERT INTO Gear (Gear_Id, fld2, fld3, fld4, fld5, fld6, fld7) " +
              " VALUES (?,?,?,?,?,?,?)";
        simpleJdbcTemplate.update(sql, 1L, 1L, 1L, "fld4", "fld5", new Date(), "fld7");
        assertEquals(1L, simpleJdbcTemplate.queryForLong("select Gear_Id from Gear where Gear_Id = 1"));
        System.out.println(gearDao);

        Gear gear = gearDao.findById(1L);
        assertNotNull("gear is null.", gear);  // <== This fails.
    }
}

The application (a Spring MVC site) works fine with the DAO's. What could be happening? And where would I begin to look for a solution?

  1. The DAO somehow has a different dataSource than the simpleJdbcTemplate. Not sure how this would be, though, since there's only one dataSource defined in the DaoTests-context.xml file.
  2. Hibernate requires all foreign key relations to be present in order to select out the Gear object. There are a couple of joins that are not present since I'm hardcoding those in fld2/fld3/fld4.
  3. The DAO won't act on the uncommitted data. But why would the simpleJdbcTemplate honor this? I'd assume they both do the same thing.
  4. Underpants gnomes. But where's the profit?
A: 

What a difference a couple hours of sleep makes. I woke up and thought "I should check the logs to see what query is actually being executed." And of course it turns out that hibernate was configured to generate some inner joins for a few of the foreign keys. Once I supplied those dependencies it worked like a charm.

I'm loving the automatic rollback on every test concept. Integration tests, here I come!

roufamatic