gpt4 book ai didi

spring - Jpa测试和Spring自动回滚

转载 作者:行者123 更新时间:2023-11-28 20:20:58 26 4
gpt4 key购买 nike

我指的是 Spring Roo In Action(Manning 的书)。书中某处说“Roo 将测试类标记为@Transactional,以便单元测试自动回滚任何更改

这里是说明方法:

@Test
@Transactional
public void addAndFetchCourseViaRepo() {
Course c = new Course();
c.setCourseType(CourseTypeEnum.CONTINUING_EDUCATION);
c.setName("Stand-up Comedy");
c.setDescription(
"You'll laugh, you'll cry, it will become a part of you.");
c.setMaxiumumCapacity(10);

c.persist();
c.flush();
c.clear();
Assert.assertNotNull(c.getId());

Course c2 = Course.findCourse(c.getId());
Assert.assertNotNull(c2);
Assert.assertEquals(c.getName(), c2.getName());
Assert.assertEquals(c2.getDescription(), c.getDescription());
Assert.assertEquals(
c.getMaxiumumCapacity(), c2.getMaxiumumCapacity());
Assert.assertEquals(c.getCourseType(), c2.getCourseType());
}

但是,我不明白为什么如果没有发生 RuntimeException,此方法中的更改会自动回滚...

最佳答案

引自 documentation :

By default, the framework will create and roll back a transaction for each test. You simply write code that can assume the existence of a transaction. [...] In addition, if test methods delete the contents of selected tables while running within a transaction, the transaction will roll back by default, and the database will return to its state prior to execution of the test. Transactional support is provided to your test class via a PlatformTransactionManager bean defined in the test's application context.

因此,换句话说,运行测试的 SpringJUnit4ClassRunner 总是在测试执行后进行事务回滚。

关于spring - Jpa测试和Spring自动回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11329411/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com