title: How to properly mock a private ExecutorService's submit method in JMockit
body: <p>I have a class which contains a private ExecutorService instance. Within the class I have a method which runs the submit method and catches the RejectedExecutionException. However I am having trouble in mocking the ExecutorService instance to throw the exception so that I can complete my test coverage. I am using JMockit 1.45.</p>
  
  <p>I have already gone through the JMockit tutorial and other sites; whether i use @Mocked, @Capturing, or even create a new fake class it doesn't seem to work.</p>
  
  <pre><code>// Implemented Class:
  public class TaskRegister {
  
      private ExecutorService executor;
  
      public TaskRegister() {
          this.executor = Executors.newFixedThreadPool(5);
      }
  
      public void executeTask(Runnable task) {
          try {
              this.executor.submit(task);
          } catch (RejectedExecutionException e) {
              System.out.println(e.getMessage);
          }
      }
  }
  
  
  // Unit Test Class:
  public class TestTaskRegister {
      @Tested
      private TaskRegister tested;
  
      private static int counter;
  
      @Test // this works
      public void runNormalTask() throws InterruptedException {
          counter = 0;
          Runnable mockTask = new Runnable() {
              counter++;
          }
  
          tested.executeTask(mockTask);
          Thread.sleep(100); // Allow executor to finish other thread.
          assertEquals(1, counter);
      }
  
      @Test // this doesn't work, will have missing invocation error.
      public void throwsError (@Capturing ExecutorService executor) throws InterruptedException {
          counter = 0;
  
          // somehow the tested class still runs the actual executor 
          // and not the mocked one.
          new Expectations() {{
               executor.submit((Runnable) any);
               result = new RejectedExecutionException();
          }};
  
          Runnable mockTask = new Runnable() {
              // some task
          }
  
          tested.executeTask(mockTask);
          Thread.sleep(100);
          assertEquals(0, counter);
      }
  }
  </code></pre>
  
  <p>I expect the @Capturing to intercept the real executor implementation and throw the exception upon executor.submit being called, but it isn't doing that.</p>