gpt4 book ai didi

spring - @NotTransactional替代

转载 作者:行者123 更新时间:2023-12-04 13:19:59 27 4
gpt4 key购买 nike

我正在进行单元测试,该单元测试通过DAO将信息提交到Oracle数据库,然后检索它并检查所有内容是否不变。

测试类中还有其他单元测试,在该类的顶部,我有:

@TransactionConfiguration (defaultRollback = true)

我想知道如何删除@NotTransactional。我没有在类上指定Transactional,因此默认情况下没有测试应该是这样的。由于这是它自己的测试,因此我不知道@BeforeTransaction(或After)注释是否正确。

最大的问题是,如果没有@NotTransactional,则好像未运行unsubscribe()函数。 (废纸flag标志不变。)

在完成@ rollback = false和@NonTransactional的情况下再次运行测试,我看到测试完成后在数据库中将垃圾桶标记正确设置为true。
@RunWith (SpringJUnit4ClassRunner.class)
@TransactionConfiguration (defaultRollback = true)
public class DatabaseTest {

@Autowired (required = true)
private FooDao<Foo> fooDao;

@Autowired (required = true)
private FooService fooService;

// other tests here that are marked @Transactional.

@Test
@NotTransactional
public void testDelete() {
Foo foo = new foo();
foo.setTrashFlag(false);
foo.setId(123);

fooDao.create(foo);

Foo fooFromDb = fooService.getFromDbById(123);
assertNotNull(fooFromDb);

fooService.unsubscribe(123); // among other things,
// **sets trash flag to true.**

// sqlSession.flushStatements(); // doesn't seem to commit the unsubscribe action


// getFromDbById() returns ONLY Foos with trash set to false, so we expect
// nothing returned here as we've just set trash to true, using unsubscribe().

Foo trashedFoo = fooService.getFromDbById(123);
assertNull(trashedFoo);

谢谢!

最佳答案

@Rollback(false)并不总是足够的,它仅意味着在测试结束时不会回滚事务。但是它仍然在事务中运行测试,有时会导致与其他正在运行的事务发生冲突。

如Spring所建议的,您有两种选择:

  • 将测试类分为两部分,事务测试可以是用@Transactional注释的in测试类,而测试类中的非事务测试则没有事务注释。
  • 使用方法注释而不是类注释,用@Transactional注释每个事务测试,但将其从类范围
  • 中删除

    引用Spring documentation:

    As of Spring 3.0, @NotTransactional is deprecated in favor of moving the non-transactional test method to a separate (non-transactional) test class or to a @BeforeTransaction or @AfterTransaction method. As an alternative to annotating an entire class with @Transactional, consider annotating individual methods with @Transactional; doing so allows a mix of transactional and non-transactional methods in the same test class without the need for using @NotTransactional.

    关于spring - @NotTransactional替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15487243/

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