我正在进行单元测试,它通过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);
谢谢!
正如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
.