title: How to mock static final class
body: <p>I have the following classes, where the second class is a static final field of the first one:</p>
  
  <pre><code>public class BaseItemScan  {
  
  
      protected String initItem(){
         ...
      }
  
  }
  
  public class ItemScan extends BaseItemScan {
  
      private static final ItemFactory if = ItemFactory.getInstance();
      public void handleItem(){
         super.initItem();
         ...
      }
  
  }
  </code></pre>
  
  <p>The factory class contains a constructor and a getInstance method:</p>
  
  <pre><code>public class ItemFactory {
      private static ItemFactory INSTANCE = null;
  
      public static ItemFactory getInstance() {
          if (INSTANCE == null) {
              throw new IllegalStateException("ItemFactory not initialized!");
          } else {
              return INSTANCE;
          }
      }
  
      public ItemFactory () {
          if (INSTANCE != null) {
              throw new IllegalStateException("ItemFactory already initialized!");
          } else {
              INSTANCE = this;
          }
      }
  }
  </code></pre>
  
  <p>How can the handleItem be tested? For the following code:</p>
  
  <pre><code>public class ItemScanTest {
  
      @InjectMocks
      ItemScan itemScan= new ItemScan();
  
      @Rule
      public MockitoRule rule = MockitoJUnit.rule();
  
      @Test
      void testHandleItem() {
          itemScan.handleItem();
      }
  
  }
  </code></pre>
  
  <p>The error message is:</p>
  
  <pre><code>Caused by: java.lang.IllegalStateException: ItemFactory not initialized!
      at ItemFactory.getInstance(ItemFactory.java:)
      at ItemScan.&lt;clinit&gt;(ItemScan.java:)
  </code></pre>