spring boot junit 测试 + @transactional 传播 required_new

Cla*_*omo 5 junit spring transactions spring-test spring-boot

我想测试一个保存到我的数据库中的循环。我已经在内存中设置了一个数据库并加载了我的场景。我有一个BasicInitTest像这样命名的基本测试类

RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CentralApplication.class)
@WebAppConfiguration
@Transactional
@Ignore
public class BasicInitTest {
.......
}
Run Code Online (Sandbox Code Playgroud)

我所有的测试类都扩展了这一点,并且每个测试类都有多种@Test方法。特别是其中一个调用 a FooServiceImpl.iterateAndSave(List<FooModel>),它迭代一个列表并尝试保存单个对象。

FooServiceImpl.save(Foo)保存方法由用 注释的方法执行@Transactional(propagation=Propagation.REQUIRED_NEW)。此方法,在保存槽之前FooRepository.save(Foo),尝试查找对象来抛出异常或保存

@Transactional(propagation=Propagation.REQUIRED_NEW)
public Foo save(Foo foo) throws Exception {
   Foo f = fooRepository.findById(foo.getId);
   if(f) throw new Exception("ex");
   return fooRepository.saveAndFlush(foo);
}
Run Code Online (Sandbox Code Playgroud)

就像上面的测试仍然在第一行服务暂停一样,相反,没有@Transactional(propagation=Propagation.REQUIRED_NEW),它可以工作。

我必须使用注释来@Transactional防止异常,FooServiceImpl.iterateAndSave(List<FooModel>)因为它有一个循环来迭代每个模型对象以执行某些操作,然后保存对象。

事实上,如果我删除注释,并且保存操作会出现异常,例如ConstraintViolationException,当保存下一个对象时,我会收到此错误

HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: null id in com.projecy.Foo entry (don't flush the Session after an exception occurs)
Run Code Online (Sandbox Code Playgroud)

如何测试这个场景?