title: How to stub return value for the private method of same class using mockito
body: <p>I am working on spring based project and writing unit test case using JUnit + Mockito. I am facing a problem while stubbing boolean value to a private method of same test class (after changing access level to public, still I have failed to stub the boolean value).</p>
  
  <p>Below code snippet shows the simulation of same problem  </p>
  
  <pre class="lang-java prettyprint-override"><code>class ABC {
  
      public String method1(User userObj){
          String result = "";
  
          if(!isValidUser(userObj.getSessionID())){
              return "InvalidUser";
          } else {
             // execute some logic
          }
  
          return result;
      }
  
  
      private boolean isValidUser(String sessionId) {
          // Here it calls some other class to validate the user 
          if (sessionId == null || UserSessionPool.getInstance().getSessionUser(sessionId) == null) {
              return false;
          } else {
              return true;
          }
      } 
  }
  </code></pre>
  
  <p>Here, I would like to write a test case for method1(). In class ABC I have a method called <code>isValidUser()</code> which helps to identify the user with in a session by looking into a global session pool which holds all logged-in used details i.e. <code>UserSessionPool.getInstance().getSessionUser(sessionId)</code>. </p>
  
  <p>While testing method1(), the moment test controller triggers <code>isValidUser(userObj.getSessionID())</code> I would like to return <code>true</code> from <code>isValidUser()</code> method, so that I can continue to test rest of the implementation logic.</p>
  
  <p>So far I have tried following ways using spy and mocked object to call the <code>isValidUser()</code> method and try to return true but nothing worked well.  </p>
  
  <p><strong>Using PowerMockito</strong></p>
  
  <pre><code>PowerMockito.doNothing().when(spyed_ABC_ClassObject, "isValidUser", true);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>PowerMockito.doReturn(true).when(cntrl, "isValidUser", Mockito.anyString());
  </code></pre>
  
  <p><strong>Using Whitebox</strong></p>
  
  <pre><code>Whitebox.invokeMethod(spyed_ABC_ClassObject, "isValidUser", Mockito.anyString());
  </code></pre>
  
  <p><strong>Using Mockito.when</strong></p>
  
  <pre><code>when(spyed_ABC_ClassObject.isValidUser(Mockito.anyString())).thenReturn(true);
  </code></pre>
  
  <p>or</p>
  
  <pre><code>Mockito.doNothing().when(spyed_ABC_ClassObject).isValidUser(Mockito.anyString());
  </code></pre>