微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

春天 – @NotTransactional替代品

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

测试类中还有其他单元测试,在课程顶部我有

@TransactionConfiguration (defaultRollback = true)

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

最大的问题是没有@Nottransactional,似乎没有运行unsubscribe()函数. (垃圾标志不变.)

再次运行测试,@ rollback = false和@NonTransactional存在,我在测试完成后在数据库中看到trash标记正确设置为true.

@RunWith (SpringJUnit4ClassRunner.class)
@TransactionConfiguration (defaultRollback = true)
public class DatabaseTest {

    @Autowired (required = true)
    private FooDaorequired = 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注释的测试类中,而在没有事务注释的测试类中进行非事务测试.
>使用方法注释而不是类注释,使用@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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐