title: How do I mock Spring ApplicationContext's getBean method using Mockito for writing unit tests with TestNG?
body: <p>I am writing unit tests for the following class</p>
  
  <p>Class to Be Tested:</p>
  
  <pre><code>public class RandomManager {
          @Autowired
          private ApplicationContext context;
  
          @Autowired
          private ClassA objectA;
  
          public void methodToBeTested() {
              objectA.methodToBeVerified(context.getBean(Random.class,"Yaswanth","Yaswanth"));
          }
      }
  </code></pre>
  
  <p>Below is the test class:</p>
  
  <pre><code>public class RandomManagerTest {
  
      @Mock
      private ClassA objectA;
  
      @Mock
      private ApplicationContext context;
  
      @InjectMocks
      private RandomManager randomManager;
  
      @BeforeTest
      public void before() {
          MockitoAnnotations.initMocks(this);
          doReturn(any(Random.class)).when(context)
              .getBean(any(Class.class), any(), any());
      }
  
      @Test
      public void methodToBeTestedTest() {
          Random randomObject = new RandomObject("Yaswanth", "Yaswanth");
          randomManager.methodToBeTested();
          verify(objectA).methodToBeVerified(randomObject);
      }
  }
  </code></pre>
  
  <p>The above code fails in the before method when I am trying to stub the
  applicationContext mock. I get the following error.</p>
  
  <blockquote>
    <p>You cannot use argument matchers outside of verification or stubbing.
    Examples of correct usage of argument matchers:
       when(mock.get(anyInt())).thenReturn(null);
       doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
        verify(mock).someMethod(contains("foo"))</p>
    
    <p>This message may appear after an NullPointerException if the last
    matcher is returning an object  like any() but the stubbed method
    signature expect a primitive argument, in this case, use primitive
    alternatives.
        when(mock.get(any())); // bad use, will raise NPE
        when(mock.get(anyInt())); // correct usage use</p>
    
    <p>Also, this error might show up because you use argument matchers with
    methods that cannot be mocked. Following methods <em>cannot</em> be
    stubbed/verified: final/private/equals()/hashCode(). Mocking methods
    declared on non-public parent classes is not supported.</p>
  </blockquote>
  
  <p>Can anyone please help me understand what am I doing wrong in the
  above code?</p>
  
  <p>Note: I am using TestNG and Mockito. I can extend
  <code>AbstractTestNGSpringContextTests</code> and use a <code>spring-test.xml</code>, declare my
  beans and autowire applicationContext. I feel that is an overkill for
  my use case. I need to just mock applicationContext's getBean method.</p>