TransactionFilter implements ContainerRequestFilter, ContainerResponseFilter { @Override public void filter(final ContainerRequestContext requestContext) throws IOException { Session s = sessionProvider.get(); s.getTransaction().begin(); } @Inject  TransactionFilter(final Provider<Session> sessionProvider); @Override void filter(final ContainerRequestContext requestContext); @Override void filter(final ContainerRequestContext requestContext,
                       final ContainerResponseContext responseContext);  }
@Test public void testRequestFilter() throws Exception { TransactionFilter filter = new TransactionFilter(mockSessionProvider); filter.filter(requestContext); Mockito.verifyNoMoreInteractions(requestContext); Mockito.verify(mockTransaction, times(1)).begin(); }
@Test public void testResponseFilter() throws Exception { TransactionFilter filter = new TransactionFilter(mockSessionProvider); filter.filter(requestContext, responseContext); Mockito.verifyNoMoreInteractions(requestContext); Mockito.verifyNoMoreInteractions(responseContext); Mockito.verify(mockTransaction, times(1)).commit(); }
@Test public void testResponseFilterNoActiveState() throws Exception { List<TransactionStatus> statuses = Arrays.stream(TransactionStatus.values()) .filter(t -> !t.equals(TransactionStatus.ACTIVE)) .collect(Collectors.toList()); for (TransactionStatus s : statuses) { doReturn(s).when(mockTransaction).getStatus(); TransactionFilter filter = new TransactionFilter(mockSessionProvider); filter.filter(requestContext, responseContext); Mockito.verifyNoMoreInteractions(requestContext); Mockito.verifyNoMoreInteractions(responseContext); Mockito.verify(mockTransaction, times(0)).commit(); } }
@Test public void testResponseFilterError() throws Exception { Mockito.doThrow(HibernateException.class) .when(mockTransaction) .commit(); TransactionFilter filter = new TransactionFilter(mockSessionProvider); filter.filter(requestContext, responseContext); Mockito.verifyNoMoreInteractions(requestContext); Mockito.verify(mockTransaction, times(1)).commit(); Mockito.verify(mockTransaction, times(1)).rollback(); Mockito.verify(responseContext, times(1)) .setEntity(Matchers.any()); Mockito.verify(responseContext, times(1)) .setStatus(Status.INTERNAL_SERVER_ERROR.getStatusCode()); Mockito.verify(responseContext, times(1)) .setEntity(Matchers.any()); Mockito.verifyNoMoreInteractions(responseContext); }