UserCreatorInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable, ApiException { final String email = (String) invocation.getArguments()[0]; try { userManager.getByEmail(email); return invocation.proceed(); } catch (NotFoundException e) { } final Object proceed = invocation.proceed(); try { final User createdUser = (User) proceed; notificationSender.sendNotification(createdUser.getName(), createdUser.getEmail(), false); } 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")); when(invocation.getArguments()).thenReturn(new Object[] {null, "token123"}); interceptor.invoke(invocation); verifyZeroInteractions(notificationSender); }
@Test public void shouldSendEmailWhenUserWasCreated() throws Throwable { final Method method = UserCreator.class.getMethod( "createUser", String.class, String.class, String.class, String.class); when(invocation.getMethod()).thenReturn(method); when(invocation.proceed()).thenReturn(user); when(user.getEmail()).thenReturn(recipient); when(user.getName()).thenReturn("user123"); when(userManager.getByEmail(recipient)).thenThrow(new NotFoundException("")); when(invocation.getArguments()).thenReturn(new Object[] {recipient}); interceptor.invoke(invocation); verify(notificationSender).sendNotification(eq("user123"), eq(recipient), eq(false)); }
@Test public void shouldNotSendEmailWhenUserCreatorProvideExistingUser() throws Throwable { final Method method = UserCreator.class.getMethod( "createUser", String.class, String.class, String.class, String.class); when(invocation.getMethod()).thenReturn(method); when(invocation.proceed()).thenReturn(user); when(user.getEmail()).thenReturn(recipient); when(user.getName()).thenReturn("user123"); when(invocation.getArguments()).thenReturn(new Object[] {recipient}); interceptor.invoke(invocation); verify(notificationSender, never()).sendNotification(any(), anyString(), anyBoolean()); }