小编典典

@Test之后的回滚事务

spring

首先,我在StackOverflow上发现了很多与此相关的线程,但是它们都没有真正帮助我,所以很抱歉提出可能重复的问题。

我正在使用spring-test运行JUnit测试,我的代码如下所示

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {})
public class StudentSystemTest {

    @Autowired
    private StudentSystem studentSystem;

    @Before
    public void initTest() {
    // set up the database, create basic structure for testing
    }

    @Test
    public void test1() {
    }    
    ...  
}

我的问题是我希望我的测试不影响其他测试。因此,我想为每个测试创建类似回滚的内容。我为此进行了很多搜索,但到目前为止我什么都没找到。我为此使用Hibernate和MySql


阅读 837

收藏
2020-04-12

共1个答案

小编典典

只需@Transactional在测试之上添加注释:

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class StudentSystemTest {

默认情况下,Spring将启动围绕你的测试方法和@Before/ @After回调的新事务,并在最后回滚。默认情况下它可以工作,在上下文中有一些事务管理器就足够了。

来自:10.3.5.4事务管理(粗体):

在TestContext框架中,事务由TransactionalTestExecutionListener进行管理。请注意,即使你未在测试类上显式声明,它TransactionalTestExecutionListener也是默认配置的@TestExecutionListeners。但是,要启用对事务的支持,必须PlatformTransactionManager在由@ContextConfiguration语义加载的应用程序上下文中提供一个bean 。此外,你必须@Transactional在类或方法级别为测试声明。

2020-04-12