title: Java: Junit a class with Inject annotation
body: <pre><code>@Singleton
  public class RealWorkWindow implements WorkWindow {
  
      @Inject private Factory myFactory;
  
      public RealWorkWindow (
              LongSupplier longSupplier
      ) {
          defaultWindow = myFactory.create(() -&gt; 1000L);
          workWindow = myFactory.create(longSupplier);
      } 
      ...
  </code></pre>
  
  <p>As you can see I am Injecting a factory class (injected via FactoryModuleBuilder)</p>
  
  <p>Test code</p>
  
  <pre><code>@Test
  public class RealWorkWindowTest {
      private RealWorkWindow testWindow;
  
      @BeforeMethod
      void setup() {
          MockitoAnnotations.initMocks(this);
  
          testWindow = spy(new RealWorkWindow(() -&gt; 1L));
      }
  </code></pre>
  
  <p>Factory.py</p>
  
  <pre><code>public interface RealWorkWindowFactory {
      RealWorkWindowFactory create(LongSupplier longSupplier);
  }
  </code></pre>
  
  <p>Module</p>
  
  <pre><code>install(new FactoryModuleBuilder()
                          .implement(WorkWindow.class, RealWorkWindow.class)
                          .build(RealWorkWindowFactory.class));
  </code></pre>
  
  <p>When I run the test <code>RealWorkWindowTest</code> the test fails with NPE that factory does not exists, which makes sense since I dont think injection runs.</p>
  
  <p>How can I test with Injection in junit? or mock properly?</p>
  
  <p>Similar to the problem describe in <a href="https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html" rel="nofollow noreferrer">https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html</a></p>
  
  <p>But the problem that I have is that mock is used <strong>IN</strong> constructor so it's still a null when instantiate the test object (because i have not called Mockito.init yet)</p>