title: How to android unit test and mock a static method
body: <p>Hi I really hope you can help me, I feel like I've been pulling my hair out for days.</p>
  
  <p>I'm trying to write unit tests for a method A. Method A calls a static method B. I want to mock static method B.</p>
  
  <p>I know this has been asked before, but I feel Android has matured since then, and there must be a way to do such a simple task without re-writing the methods I want to test.</p>
  
  <p>Here is an example, first the method I want to test:</p>
  
  <pre><code>public String getUserName(Context context, HelperUtils helper) {
      if(helper == null){
          helper = new HelperUtils();
      }
      int currentUserId = helper.fetchUsernameFromInternet(context);
  
      if (currentUserId == 1) {
          return "Bob";
      } else {
          return "Unknown";
      }
  }
  </code></pre>
  
  <p>Next the static method I want to mock:</p>
  
  <pre><code>public class HelperUtils {
      public static int fetchUsernameFromInternet(Context context) {
          int userid = 0;
  
          Log.i("HelperUtils ", "hello");
  
          return userid;
      }
  }
  </code></pre>
  
  <p>In other languages this is so easy but I just can't make it work in Android. 
  I've tried Mockito, but it appears static methods aren't supported</p>
  
  <pre><code>HelperUtils helper = Mockito.mock(HelperUtils.class);
  Mockito.when(helper.fetchUsernameFromInternet(getContext())).thenReturn(1);
  </code></pre>
  
  <p>This errors</p>
  
  <blockquote>
    <p>org.mockito.exceptions.misusing.MissingMethodInvocationException</p>
  </blockquote>
  
  <p>I've tried Powermock but I'm not completely sure this is supported by Android. I managed to get powermock running using androidCompile in my gradle file but I get this error:</p>
  
  <blockquote>
    <p>Error:Execution failed for task ':app:dexDebugAndroidTest'. com.android.ide.common.process.ProcessException:</p>
  </blockquote>
  
  <p>Not to mention <code>PowerMockito.mockStatic(HelperUtils.class);</code> Doesn't return anything, so I don't know what to pass into my getUsername method!</p>
  
  <p>Any help would be so very much appreciated.</p>