CreateUserInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable, ApiException { Object proceed = invocation.proceed(); String userName; String userEmail; try { final Response response = (Response) proceed; final UserDto createdUser = (UserDto) response.getEntity(); userName = createdUser.getName(); userEmail = createdUser.getEmail(); final String token = (String) invocation.getArguments()[1]; notificationSender.sendNotification(userName, userEmail, token == null); } catch (Exception e) { LOG.warn("Unable to send creation notification email", e); } return proceed; }  @Override Object invoke(MethodInvocation invocation);  }
@Test(expectedExceptions = ConflictException.class) public void shouldNotSendEmailIfInvocationThrowsException() throws Throwable { when(invocation.proceed()).thenThrow(new ConflictException("conflict")); interceptor.invoke(invocation); verifyZeroInteractions(notificationSender); }
@Test public void shouldSendEmailWhenUserWasCreatedByUserServiceWithToken() throws Throwable { final Method method = UserService.class.getMethod("create", UserDto.class, String.class, Boolean.class); when(invocation.getMethod()).thenReturn(method); final Object[] invocationArgs = new Object[method.getParameterCount()]; invocationArgs[1] = "token123"; when(invocation.getArguments()).thenReturn(invocationArgs); when(invocation.proceed()).thenReturn(response); when(response.getEntity()) .thenReturn(DtoFactory.newDto(UserDto.class).withEmail(recipient).withName("user123")); interceptor.invoke(invocation); verify(notificationSender).sendNotification(eq("user123"), eq(recipient), eq(false)); }
@Test public void shouldSendEmailWhenUserWasCreatedByUserServiceWithDescriptor() throws Throwable { final Method method = UserService.class.getMethod("create", UserDto.class, String.class, Boolean.class); when(invocation.getMethod()).thenReturn(method); final Object[] invocationArgs = new Object[method.getParameterCount()]; when(invocation.getArguments()).thenReturn(invocationArgs); when(invocation.proceed()).thenReturn(response); when(response.getEntity()) .thenReturn(DtoFactory.newDto(UserDto.class).withEmail(recipient).withName("user123")); interceptor.invoke(invocation); verify(notificationSender).sendNotification(eq("user123"), eq(recipient), eq(true)); }