Spring Test:测试dao后回滚数据库

时间:2016-12-09 09:53:29

标签: java spring

我正在寻找所有互联网,我已经测试了许多东西,但我找不到适用于我的代码的答案。

我想在运行测试后滚动我的数据库(或者每次测试后我都不在乎)

目前这是我的代码:

@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();
    }
}

所以从我读过的内容来看@Transactional应该默认回滚我的交易。但事实并非如此。为什么?

(我试图将@Transactional添加到dao和服务但它不会改变任何东西)

2 个答案:

答案 0 :(得分:2)

如果您未在测试类中使用SpringJUnit4ClassRunner runner,则会忽略@Transactional注释。

尝试添加它:

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

答案 1 :(得分:0)