title: How to mock sharedpreferences for android instrumentation tests?
body: <p>I have a preference util class to store and retrieve the data in shared preferences in a single place. </p>
  
  <p><strong>Prefutils.java:</strong></p>
  
  <pre><code>public class PrefUtils {
    private static final String PREF_ORGANIZATION = "organization";
  
    private static SharedPreferences getPrefs(Context context) {
      return PreferenceManager.getDefaultSharedPreferences(context);
    }
  
    private static SharedPreferences.Editor getEditor(Context context) {
      return getPrefs(context).edit();
    }
  
    public static void storeOrganization(@NonNull Context context,
        @NonNull Organization organization) {
      String json = new Gson().toJson(organization);
      getEditor(context).putString(PREF_ORGANIZATION, json).apply();
    }
  
    @Nullable public static Organization getOrganization(@NonNull Context context) {
      String json = getPrefs(context).getString(PREF_ORGANIZATION, null);
      return new Gson().fromJson(json, Organization.class);
    }
  }
  </code></pre>
  
  <p>Sample code showing PrefUtils usage in <strong>LoginActivity.java:</strong></p>
  
  <pre><code>@Override public void showLoginView() {
      Organization organization = PrefUtils.getOrganization(mActivity);
      mOrganizationNameTextView.setText(organization.getName());
    }
  </code></pre>
  
  <p>List of <code>androidTestCompile</code> dependencies in <strong>build.gradle:</strong></p>
  
  <pre><code>// Espresso UI Testing dependencies.
    androidTestCompile "com.android.support.test.espresso:espresso-core:$project.ext.espressoVersion"
    androidTestCompile "com.android.support.test.espresso:espresso-contrib:$project.ext.espressoVersion"
    androidTestCompile "com.android.support.test.espresso:espresso-intents:$project.ext.espressoVersion"
  
    androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
    androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2:'
  </code></pre>
  
  <p><strong>src/androidTest/../LoginScreenTest.java</strong></p>
  
  <pre><code>@RunWith(AndroidJUnit4.class) @LargeTest public class LoginScreenTest {
  
  @Rule public ActivityTestRule&lt;LoginActivity&gt; mActivityTestRule =
        new ActivityTestRule&lt;&gt;(LoginActivity.class);
  
    @Before public void setUp() throws Exception {
      when(PrefUtils.getOrganization(any()))
            .thenReturn(HelperUtils.getFakeOrganization());
    } 
  }
  </code></pre>
  
  <p>The above code to return <code>fakeOrganization</code> was not working, running the tests on login activity results in NullPointerException in line <code>mOrganizationNameTextView.setText(organization.getName());</code> defined in the above LoginActivity.java class.</p>
  
  <p>How to solve the above issue?</p>