title: Unit Testing Interceptors with Guice and JMockit
body: <p>I'm new to writing unit tests for aspects. After some reading on unit testing aspect, I arrived at the conclusion that there two types of tests to write: testing the logic of the aspect, and testing the interception (i.e., is it intercepting correctly). I have a unit test for the logic part. However, I've been struggling with coming up with a test for the interception part.</p>
  
  <p>I'm writing my tests using JUnit 4, JMockit, and Guice (for CDI and AOP).</p>
  
  <p>The class below is my aspect, which logs the execution time of a method call.</p>
  
  <pre><code>class ExecutionTime implements MethodInterceptor {
      private static final Logger logger = ...
      public Object invoke(MethodInvocation invocation) throws Throwable {
          final long start = System.nanoTime();
          try {
              return invocation.proceed();
          } finally {
              final long end = System.nanoTime();
              logger.trace(...);
          }
      }
  }
  </code></pre>
  
  <p>In Guice, I created a <code>Module</code> that is used to initialize an injector. The code is as follows. The binding says that any class and method that is not annotated with <code>@DoNotProfile</code> is to be ignored by the <code>ExecutionTime</code> aspect. </p>
  
  <pre><code>class ProfilingModule extends AbstractModule {
      public void configure() {
          bindInterceptor(not(annotatedWith(DoNotProfile.class)),
              not(annotatedWith(DoNotProfile.class)), new ExecutionTime());
      }
  }
  </code></pre>
  
  <p>Next, I defined a test class where I can test whether the methods are intercepted correctly. Some of the methods are annotated with <code>@DoNotProfile</code>.</p>
  
  <pre><code>class TestClass {
      public void methodA() {}
      @DoNotProfile public void methodB() {}
      ...
  }
  </code></pre>
  
  <p>Finally, in my test class, I have the following code in my test method.</p>
  
  <pre><code>@Test
  public void test() throws Throwable {
      Injector injector = Guice.createInjector(new ProfilingModule());
      ... // not sure what to do next
  }
  </code></pre>
  
  <p>I'm unsure of what to do next. I have tried the following.</p>
  
  <ol>
  <li>I created another interceptor to intercept the <code>invoke</code> method of the <code>ExecutionTime</code> class. However, I was unable to get that working.</li>
  <li>I created a test interceptor with the same bindings as the <code>ExecutionTime</code> and a test module to go with it. That is, <code>.createInjector(new TestModule())</code>. But I realized that this defeated the purpose of this test, which is to test that the wiring works correctly.</li>
  </ol>
  
  <p>I appreciate any insights and help on this matter.</p>