简体   繁体   English

@Transactional不会在JUnit测试中回滚

[英]@Transactional does not rollback in JUnit test

I have 2 JUnit tests in the same test class each one marked as @Transactional, the first one create users and the second one create users and check that we can get these users. 我在同一个测试类中有2个JUnit测试,每个测试标记为@Transactional,第一个创建用户,第二个创建用户并检查我们是否可以获得这些用户。

The problem is that when the second test runs, users created by the first test is still in the DB. 问题是当第二次测试运行时,第一次测试创建的用户仍然在数据库中。

@Test
@Transactional
public void testCreateUser() throws Exception

@Test
@Transactional
public void testGetUserById() throws Exception

Do you have any idea why @Transactional is not working well in the same test class? 您是否知道为什么@Transactional在同一个测试类中运行不正常? Furthermore data is rolled back at the end of the test class. 此外,数据在测试类结束时回滚。

I'm using Spring boot + Mysql + Hibernate. 我正在使用Spring启动+ Mysql + Hibernate。

Thank you for your time. 感谢您的时间。

Try something like this and take care about classpath of your ...context.xml. 尝试这样的事情,并注意你的... context.xml的类路径。 You can also move @Transactional above class if you want every method to be transactional or above each method you want. 如果您希望每个方法都是事务性的,或者高于您想要的每个方法,您也可以将@Transactional移到类之上。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/config/your-context.xml","classpath:/config/ehcache.xml"})
@Transactional
@WebAppConfiguration
public class IntegrationTests {

@Autowired
private ApplicationContext appContext;

@Autowired
public FileDao fileDao;

@Autowired
public SessionFactory sessionFactory;

@Test
public void test1() throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException{
    ....
    ....
    ....
    }
}

添加到配置类@EnableTransactionManagement

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM