title: Testing Annotation based RequestInterceptor
body: <p>I wanted to do so custom logic(Record the request and response) on some routes. Based on some research I came decided to use AnnotationBased RequestInterceptor. This is my code for interceptor.</p>
  
  <pre><code>public class CustomInterceptor extends HandlerInterceptorAdapter {
  @Override
  public void afterCompletion(final HttpServletRequest request,
                              final HttpServletResponse response,
                              final Object handler,
                              final Exception ex) {
       if (handler != null &amp;&amp; handler instanceof  HandlerMethod) {
          HandlerMethod handlerMethod = (HandlerMethod) handler;
          CustomRecord annotation = AnnotationUtils.getAnnotation(handlerMethod.getMethod(), CustomRecord.class);
          if (annotation != null) {
                // Record Request and Response in a File.
          }
  }
  </code></pre>
  
  <p>Now this class is working as expected but I was unable to unit test this function.</p>
  
  <ul>
  <li>I first thought of trying a creating an HandlerMethod Object but I
  did not get anywhere.</li>
  <li><p>Second I tried to use PowerMokito. This was my test code:</p>
  
  <pre><code>@RunWith(PowerMockRunner.class)
  @PrepareForTest(CustomInterceptor.class)
  @PowerMockIgnore("javax.management.*")
  public class CustomInterceptorTest {
  @Test
  public void restAnnotationRecording_negetivecase() {
    HandlerMethod mockHandler = mock(HandlerMethod.class);
    PowerMockito.mockStatic(AnnotationUtils.class);
    when(AnnotationUtils.getAnnotation(mockHandler.getMethod(), 
         CustomRecord.class).thenReturn(null);
    // Verify file is not saved
  }
   // A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() methodcannot be saved.
  @Test
  public void restAnnotationRecording_happycase() {
      HandlerMethod mockHandler = mock(HandlerMethod.class);
      PowerMockito.mockStatic(AnnotationUtils.class);
      when(AnnotationUtils.getAnnotation(mockHandler.getMethod(), CustomRecord.class).thenReturn(mockAnnotation);
      // Verify file is saved
  }
  }
  </code></pre>
  
  <ul>
  <li>This gives an Error A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies  with doReturn|Throw() family of methods.</li>
  </ul></li>
  </ul>
  
  <p>I wanted to check if there is any method to test the Interceptor. I am a newbie in Java, thanks for help.</p>