Issue
I use HSQLDB for testing purpose. The problem is that when I add some data in init()
method, then I can get that data only from the test which did run first.
@Before
public void init() {
if(isRun)
return;
isRun = true;
Role role = new Role();
role.setId(1);
role.setType("User");
roleDAO.save(role);
User user = new User();
user.setCredits(1000);
user.setEmail("[email protected]");
user.setUsername("User");
user.setPassword("qwerty");
user.setRoles(new HashSet<Role>(Arrays.asList(roleDAO.findById(1))));
userDAO.save(user);
User user2 = new User();
user2.setCredits(1000);
user2.setEmail("[email protected]");
user2.setUsername("User2");
user2.setPassword("qwerty");
user2.setRoles(new HashSet<Role>(Arrays.asList(roleDAO.findById(1))));
userDAO.save(user2);
}
@Test
public void findUserByIdTest() {
User user = userDAO.findByUsername("User");
assertEquals(userDAO.findById(user.getId()), user);
}
@Test
public void addUserTest() {
User user = new User();
user.setCredits(1000);
user.setEmail("[email protected]");
user.setPassword("qwerty");
user.setUsername("Antony");
user.setRoles(new HashSet<Role>(Arrays.asList(roleDAO.findById(1))));
userDAO.save(user);
assertEquals(userDAO.findByUsername("Antony"), user);
}
@Test
public void updateUserTest() {
User user = userDAO.findByUsername("User");
user.setCredits(0);
assertEquals(userDAO.findByUsername("User").getCredits(), (Integer) 0);
}
@Test
public void removeUserTest() {
userDAO.remove(userDAO.findByUsername("User"));
assertNull(userDAO.findByUsername("User"));
}
So happens that removeUserTest()
method always runs first and when I findAll()
data then I see the data I set in init()
method. After that, others test methods run but if I do findAll()
there, it just returns nothing meaning no data exists.
In addition, I have set hibernate.hbm2ddl.auto=create.
What am I missing here? Why I can get data in the first running method but in others the data just disappears.
Solution
It's expected: Spring repository tests are transactional and the transaction is rollbacked at the end of each test by default.
Even if you choose not to rollback, every test should be independant from the others, and should be able to run alone. You should not rely on the execution order either. Your findUserByIdTest()
would fail if removeUserTest()
runs first.
So, start by cleaning the database and to insert the test data before each test. If you let Spring rollback after each test, cleaning is not necessary, but you should still insert the test data before each test.
Incrementing IDs should not be a problem: you just need to stire the created entities or their IDs in fields of the test, and refer to these entities and their IDs instead of using hard-coded IDs in the test.
Answered By - JB Nizet