samedi 27 octobre 2018

Data is autodeleted from in-memory database

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("User@test.com");
    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("User2@test.com");
    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("Antony@test.com");
    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.

Aucun commentaire:

Enregistrer un commentaire