Reputation: 3992
I got some unit test that stores some Person
data into the database. To do this i use the EntityManagerFactory
.
@Test
public void findPersonById() {
personDao.savePerson(new Person("Hans"));
Person person = new Person("Peter");
personDao.savePerson(person);
Long id = person.getId();
flushAndClear();
person = personDao.findById(id);
assertThat(person.getName(), is("Peter"));
}
where
private EntityManager entityManager;
public Person savePerson(Person person) {
entityManager.persist(person);
return person;
}
and
public Person findById(Long id) {
Person person = entityManager.find(Person.class, id);
return person;
}
with this Base-Test-class
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
public class AbstractDaoTest {
protected EntityManager entityManager = Persistence.createEntityManagerFactory("DefaultPersistenceUnit")
.createEntityManager();
protected PersonDao personDao = new PersonDao();
@Before
public void setUp() {
personDao.setEntityManager(entityManager);
entityManager.getTransaction().begin();
}
@After
public void tearDown() {
entityManager.getTransaction().rollback();
}
protected void flushAndClear() {
entityManager.flush();
entityManager.clear();
}
}
My unit test runs green but when i debug this test, i can't see any data on the db (using squirrel). It doesn't matter in which step the debugger currently is, the Tables are always empty. I am using the following configuration for squirrel:
jdbc:h2:file:~/test;DB_CLOSE_DELAY=-1;LOCK_MODE=0;AUTO_SERVER=TRUE
with Driver: H2
Can you help with this issue?
Upvotes: 0
Views: 2458
Reputation: 2052
This has happened because your test cases are not properly designed.
Firstly, If you wish the data to be added to the database, you should commit the changes after any update/insert operation. You have to do a rollback only if there are any exceptions during transactions.
Design your tests some thing like this.
@BeforeTest
public void setUp() {
personDao.setEntityManager(entityManager);
entityManager.getTransaction().begin();
}
@AfterTest
public void tearDown() {
// TODO clear all inserted data either using sql statement or JPA
//Rollback only if there is any exception
entityManager.getTransaction().rollback();
}
@Test
public void findPersonById() {
Long id = System.currentTimeMillis();
personDao.savePerson(new Person(id,"Hans"));
entityManager.flush();
// TODO your assert statements go in here
/* Data is visible till here during your debug.
Once AfterTest is executed then the your data would be rolled back
*/
}
I have used testNG as my Unit testing tool, pls use appropriate tool based on your requirements. Also, if you are enityManager.flush() insert/update statements would be sent to the DB but wont be committed until commit instruction is sent to the DB by HIbernate. Pls refer this answer for further details
Upvotes: 1