title: Android Unit Test : how to clear SharedPreferences
body: <p>I am trying to clear all SharedPreferences added during my tests. I already read some posts and the official documentation (<a href="http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear%28%29">SharedPreferences.Editor.clear()</a>). But when I start my application after the unit tests were run, I still found test values.</p>
  
  <p>So, in the <a href="http://developer.android.com/reference/android/test/AndroidTestCase.html#tearDown%28%29">AndroidTestCase.tearDown()</a>, I make this : </p>
  
  
  
  <pre class="lang-java prettyprint-override"><code>public class PrivateStorageUtilsTest extends AndroidTestCase {
  
  private static final String KEY_SP_PACKAGE = "PrivateStorageUtilsTest";
  
      protected void setUp() throws Exception {
          super.setUp();
  
          // Clear everything in the SharedPreferences
          SharedPreferences sharedPreferences = getContext()
              .getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
          SharedPreferences.Editor editor = sharedPreferences.edit();
          editor.clear();
          editor.commit();
      }
  
      protected void tearDown() throws Exception {
          // Clear everything in the SharedPreferences
          SharedPreferences sharedPreferences = getContext().
              getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
          SharedPreferences.Editor editor = sharedPreferences.edit();
          editor.clear();
          editor.commit();
      }
  
  }
  </code></pre>
  
  <p>Every other questions I found on SO was about adding <code>commit()</code> after the <code>clear()</code>, which I already done here.</p>
  
  <p><strong>EDIT 1</strong> Adding <code>setUp()</code> method</p>
  
  <p><strong>EDIT 2</strong> Providing extended class</p>