springboot测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestServiceImplTest {
@Autowired
TestService testService;
@Test
public void add() throws Exception {
TestBean testBean = new TestBean();
testBean.setId(337595516089008160L);
System.out.println(testService.add(testBean));
}
}
这种情况下,是默认没有开启事务回滚的,当测试完成不会回滚数据.
开启测试完成回滚
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@Rollback
public class TestServiceImplTest {
@Autowired
TestService testService;
@Test
// @Rollback
public void add() throws Exception {
TestBean testBean = new TestBean();
testBean.setId(337595516089008160L);
System.out.println(testService.add(testBean));
}
}
测试完成后,会类似看到下面输出,同时数据也会回滚.
2017-07-20 16:41:25.286 INFO 12528 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test context [DefaultTestContext@a3d8174 testClass = TestServiceImplTest,
Rollback注解,默认值true,开启回滚,可以在类上,也可以方法上
@Transactional(readOnly = true) 含义.
一直以来的理解都是声明只读事务,对其进行优化,当执行插入操作的时候抛出异常.
今天将其加在一个insert方法上面,发现测试插入成功.
@Transactional(rollbackFor = Exception.class,readOnly = true)
public int add(TestBean testBean) {
int i = testMapper.insert(testBean);
return i;
}
阅读源码.
/**
* {@code true} if the transaction is read-only.
* <p>Defaults to {@code false}.
* <p>This just serves as a hint for the actual transaction subsystem;
* it will <i>not necessarily</i> cause failure of write access attempts.
* A transaction manager which cannot interpret the read-only hint will
* <i>not</i> throw an exception when asked for a read-only transaction
* but rather silently ignore the hint.
* @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()
*/
boolean readOnly() default false;
发现readOnly = true 只是对底层系统暗示要求只读事务,当底层支持时才会针对插入操作抛出异常,当不支持时,默默忽略(而大部分简单的jdbc都是不支持的)