【问题标题】:How do you get the setup method in a test (with @Before) to not rollback, even when you have a test method (with @Test) set to rollback?即使您将测试方法(使用@Test)设置为回滚,如何使测试(使用@Before)中的设置方法不回滚?
【发布时间】:2015-09-07 15:45:16
【问题描述】:

我正在 setup() 方法中加载一些测试数据。 也就是说,我希望这个测试数据设置一次,并且可用于类中的所有测试。

但是,事务测试方法(使用 @Test 和 @Rollback(true) 注释)也会导致 setup 方法回滚..

有没有办法确保只有测试方法回滚而不是设置? 注意:- 不能使用 @BeforeClass,因为我需要从 spring 上下文访问 Autowired bean,如果它被注释为 @BeforeClass,则在 setup() 的静态上下文中不可用。

谢谢, 谢卡尔


PS:在 stackoverflow 中提出了类似的问题,但从未回答:- @Rollback(false) not working on @Before using SpringJUnit4ClassRunner

【问题讨论】:

    标签: java spring junit


    【解决方案1】:

    使用@TestExecutionListener 而不是@BeforeClass。这样,您的测试上下文将在执行之前加载。此外,设置代码是外部化的,可以重复用于其他测试。

    更多信息可以在这里找到:What is the difference between @BeforeClass and Spring @TestExecutionListener beforeTestClass()

    【讨论】:

    • 我能否在我从 AbstractTestExecutionListener 扩展的类中访问 beforeTestClass 覆盖中的自动装配 bean?似乎不起作用。所有自动装配的 bean 似乎都是空的。因此,我不能使用它们来加载测试数据。
    • 猜,不能使用@Autowired注解。必须使用-testContext.getApplicationContext().getBean("")
    猜你喜欢
    • 2012-12-17
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2016-09-07
    相关资源
    最近更新 更多