title: Mockito - mock ApplicationContext
body: <p>I have a Springboot application that looks up the bean from the <code>ApplicationContext</code> at runtime based on the input parameter passed by the user. For this method, I am trying to write Mockito test cases but it is not working and throws NullPointerException.</p>
  <p>The class which bootstraps the application:</p>
  <pre><code>@SpringBootApplication
  public class MyApplication {
  
      private static ApplicationContext appContext;
      
      public static void main(String[] args) {
          appContext = SpringApplication.run(MyApplication.class, args);
      }
      
      public static ApplicationContext getApplicationContext() {
          return appContext;
      }
      
  }
  </code></pre>
  <p>Class for which I am trying to write the test cases:</p>
  <pre><code>@Service
  public class Mailbox {
  
      @Autowired
      MailProcessor processor;
      
      public void processUserInput(Envelope object) {
      
          processor.setCommand(MyApplication.getApplicationContext().getBean(object.getAction(), Command.class));
          processor.allocateEnvelopes(object);
          
      }
  } 
  </code></pre>
  <p>And my test case is as below:</p>
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  @SpringBootTest
  @ActiveProfiles(&quot;test&quot;)
  public class MailboxTest {
  
      @Mock
      MailProcessor processor;
      
      @InjectMocks
      Mailbox mailbox;
      
      @Test
      public void testProcessUserInput() {
          
          Envelope message = new Envelope();
          message.setAction(&quot;userAction&quot;);
          message.setValue(&quot;userInput&quot;);
          
          doNothing().when(processor).setCommand(any());
          doNothing().when(processor).allocateEnvelopes(any());
          
          mailbox.processUserInput(message);
          
          Mockito.verify(processor).allocateEnvelopes(any());
          
      }
      
      
  }
  </code></pre>
  <p>Whenever I run the test cases it gives the NullPointerException at <code>processor.setCommand(MyApplication.getApplicationContext().getBean(object.getAction(), Command.class));</code> in <code>Mailbox</code> class. How can I mock the ApplicationContext lookup? Am I missing any mocking step?</p>