JUnit - Test whether object was persisted or not I am using Hibernate 4 and Spring Framework 4. I wrote a simple test to check whether object was persisted or not.

All set values in confirmationEntity are required.

In this test I relly on that, that after a new object is persisted, then it is given a new id automatically.

Is this correct way how to determine if the object was persisted or not? Or is there better way? 

@Test
public void testCreated(){
    ConfirmationTypeEntity confirmationTypeEntity = confirmationTypeDao.find(1L);
    UserEntity userEntity = userDao.find(1L);

    ConfirmationEntity confirmationEntity = new ConfirmationEntity();
    confirmationEntity.setConfirmationTypeEntity(confirmationTypeEntity);
    confirmationEntity.setUserEntity(userEntity);
    confirmationEntity.setConfirmationString("5374a74e9542f");
    confirmationEntity.setConfirmationStringValidUntil(new LocalDateTime());

    confirmationDao.create(confirmationEntity);
    confirmationDao.flush();

    Assert.assertNotNull("Expected not null value.", confirmationEntity.getId());
}
I'm going to assume that you have a standard DAO setup so you should try the following.

@Test
public void testCreated(){
    ConfirmationTypeEntity confirmationTypeEntity = confirmationTypeDao.find(1L);
    UserEntity userEntity = userDao.find(1L);

    ConfirmationEntity confirmationEntity = new ConfirmationEntity();
    confirmationEntity.setConfirmationTypeEntity(confirmationTypeEntity);
    confirmationEntity.setUserEntity(userEntity);
    confirmationEntity.setConfirmationString("5374a74e9542f");
    confirmationEntity.setConfirmationStringValidUntil(new LocalDateTime());

    int countPreSave = confirmationDao.count();

    confirmationDao.create(confirmationEntity);

    /* This call has the advantage of getting Hibernate to flush the session 
     * to prevent you reading stale data in your count call.
     */
    int countPostSave = confirmationDao.count();

    assertEquals("The number of confirmations doesn't match what was expected", 
                  countPostSave,
                  countPreSave + 1);


There, you've just ensured that your object was saved correctly, and only 1 record was inserted. You can do similar things for update (ensure countPreUpdate and countPostUpdate match) and delete (ensure countPostDelete = countPreDelete - 1)

If you don't have a count() method, here is the Hibernate criteria implementation: 

@Override
public int count() {
    Criteria criteria = getCurrentSession().createCriteria(type);
    criteria.setProjection(Projections.rowCount());
    return (Integer) criteria.uniqueResult();
}