vendredi 15 avril 2016

Why isn't my entity updated when I make the test Transactional?

Given this class with two tests:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@TestPropertySource(locations = "classpath:config/application-test.properties")
public class AccountDaoTest {

    @Autowired
    private UserDao userDao;

    @Autowired
    private AccountDao accountDao;

    @Test
    public void getEmail() {
        User user = new User();
        userDao.save(user);

        Account account = new Account();
        account.setUserId(user.getId());
        account.setEmail("testemail@test.te");
        accountDao.save(account);

        Email email = accountDao.getEmailByAccountId(account.getId());
        assertThat(email, is(email));
    }

    @Test
    public void deactivate() {
        User user = new User();
        userDao.save(user);

        Account account = new Account();
        account.setUserId(user.getId());
        account.isActive(true);
        accountDao.save(account);

        accountDao.deactivateByUserId(user.getId()); // Query: UPDATE Account SET isActive = false WHERE userId = userId

        Account account2 = accountDao.findById(account.getId());
        assertThat(account2.isActive(), is(false));
    }

}

The second one fails if I annotate the class with @Transactional (account2.isActive() is still true). The main difference between both is that I'm updating the entity I save.

Does this mean that I can't run updates on such entities? Why? That doesn't make sense, given that I can insert entities and then fetch them.

I thought it could be due to the transactionality scope (it's DAO level), but then the first test would also fail because the saved User wouldn't be available by the time I try to save an Account.

Aucun commentaire:

Enregistrer un commentaire