UnitOfWorkInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { if (null == didWeStartWork.get()) { unitOfWork.begin(); didWeStartWork.set(Boolean.TRUE); } else { return invocation.proceed(); } try { return invocation.proceed(); } finally { if (null != didWeStartWork.get()) { didWeStartWork.remove(); unitOfWork.end(); } } }  @Override Object invoke(MethodInvocation invocation);  }
@Test public void assertThatSimultaneouslyUsingAnnotationOnManyLevelsWorks() throws Throwable { UnitOfWorkInterceptor unitOfWorkInterceptor = new UnitOfWorkInterceptor(); unitOfWorkInterceptor.unitOfWork = unitOfWork; unitOfWorkInterceptor.didWeStartWork.set(Boolean.TRUE); unitOfWorkInterceptor.invoke(methodInvocation); Mockito.verify(unitOfWork, Mockito.never()).begin(); Mockito.verify(unitOfWork, Mockito.never()).end(); Mockito.verify(methodInvocation).proceed(); }
@Test public void assertAnnotationStartsAndEndsNewUnitOfWork() throws Throwable { UnitOfWorkInterceptor unitOfWorkInterceptor = new UnitOfWorkInterceptor(); unitOfWorkInterceptor.unitOfWork = unitOfWork; unitOfWorkInterceptor.invoke(methodInvocation); Mockito.verify(unitOfWork).begin(); Mockito.verify(unitOfWork).end(); Mockito.verify(methodInvocation).proceed(); }