Dr.Linus
Dr.Linus

Reputation: 77

Spring Test : Rollback the database after testing the dao

I'm looking all the internet i have test many things but i can't find an answer that work on my code.

I would like to RollBack my database after running the tests (or after each test i doesn't really care)

For the moment here is my code :

@Transactional
public class ApplicationServiceTest {

    private ApplicationService applicationService;

    @Test
    public void testAddApplication() throws ExceptionMessage
    {
        Application application = applicationService.addApplication("nom", true, "domaineFonctionnel");

        // [...] testing    
    }

    //[...] @Before and @After doing things
}

public class ApplicationService{

    private ApplicationDao applicationDao;

    public Application addApplication(String nom, boolean autorise, String domaineFonctionnel)
    {
        Application application = new Application();

        // [..] Initialise application with parameters

        applicationDao.addApplication(application);     
        return application;
    }
}

public class ApplicationDao extends Dao
{

    private static EntityManagerFactory entityManagerFactory;

    public void updateApplication(Application application) {

        entityManager = entityManagerFactory.createEntityManager();

        entityManager.getTransaction().begin();
        entityManager.merge(application); 
        entityManager.getTransaction().commit();

        entityManager.close();
    }
}

So from what I've read the @Transactional should rollback by default my transactions. But it doesn't. Why?

(I have tried to add @Transactional to dao and service but it doesn't change anything)

Upvotes: 3

Views: 4726

Answers (2)

harryssuperman
harryssuperman

Reputation: 511

The davidxxx answer is right. With spring settings this is the standar behaviour.

The official Documentation to read:

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-tx-rollback-and-commit-behavior

Upvotes: 0

davidxxx
davidxxx

Reputation: 131346

If you don't use the SpringJUnit4ClassRunner runner in your test class, the @Transactional annotation is ignored.

Try by adding it:

@RunWith(SpringJUnit4ClassRunner.class)  
@Transactional
public class ApplicationServiceTest {

Upvotes: 3

Related Questions