title: How to unit test an anonymous inner class created in the constructor
body: <p>Here is the class I want to test:</p>
  
  <pre><code>public class MyView extends FrameworkView {
      public MyView(Repository repository) {
          repository.addEventListener(event -&gt; {
              refresh();
          });
      }
  }
  </code></pre>
  
  <p>and its parent:</p>
  
  <pre><code>public class FrameworkView { 
      protected final void refresh() {
          // do framework magic to refresh the view
      }
  }
  </code></pre>
  
  <p>I want to unit test MyView. I can use an ArgumentCaptor to get the listener (using Mockito):</p>
  
  <pre><code>@Test
  public void test() {
      Repository repository = mock(Repository.class);
      MyView instance = new MyView(repository);
      ArgumentCaptor&lt;EventListener&gt; listenerArgument = ArgumentCaptor.forClass(EventListener.class);
      verify(repository).addEventListener(listenerArgument.capture());
      EventListener listener = listenerArgument.getValue();
  
      // call the listener to trigger the refresh() call
      listener.handleEvent(null);
  
      // now what?
  }
  </code></pre>
  
  <p>The problem is that the <code>refresh()</code> method is in the super class (not under my control), and it's final, and has side effects which are very hard to verify. So I don't see how I can stub or override the <code>refresh()</code> method, nor how I can verify its behavior.</p>
  
  <p>The only solution I can think of now is to move the <code>refresh()</code> call into a package-private method of MyView and stub that:</p>
  
  <pre><code>public class MyView extends FrameworkView {
      public MyView(Repository repository) {
          repository.addEventListener(event -&gt; {
              doRefresh();
          });
      }
  
      void doRefresh() {
          refresh();
      }
  }
  </code></pre>
  
  <p>And then the test would become:</p>
  
  <pre><code>@Test
  public void test() {
      Repository repository = mock(Repository.class);
      MyView instance = Mockito.spy(new MyView(repository));
      ....
      verify(instance, times(1)).doRefresh();
  </code></pre>
  
  <p>But I think this is ugly. Does anybody have ideas for a nicer solution?</p>