3

Referring this SO question, I tried to save shared preferences, but my assertion fails.

This is my test class

@Test
public void testSharedPreferences(){
activity=actController.create().get();
 loginButton=(Button)activity.findViewById(R.id.loginButton);
 userName=(EditText)activity.findViewById(R.id.userName);
 userPassword=(EditText)activity.findViewById(R.id.userPassword);
 sharedPrefs =    ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext());
 sharedPrefs.edit().putString("userName", "user1").commit();

 assertThat(userName.getText().toString(),equalTo("user1"));

}

This is the code in the class under test-

public class LoginActivity extends Activity {
private EditText userName,userPassword;
 @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
       SharedPreferences sharedPreferences =PreferenceManager.getDefaultSharedPreferences(this);
         final SharedPreferences.Editor editor=sharedPreferences.edit();
         String name = sharedPreferences.getString("userName", "");
         if (!"".equalsIgnoreCase(name)) {
            userName.setText(name);
        }
}

Assertion fails and it says expected "user1" but found "".

Community
  • 1
  • 1
inquisitive
  • 3,738
  • 6
  • 30
  • 56

1 Answers1

3

Your test is creating the activity first (and triggering onCreate() too early), so your changes to the SharedPrefs have no effect. Try this instead:

@Test
public void testSharedPreferences() {
     // First set up the shared prefs
     sharedPrefs = ShadowPreferenceManager.getDefaultSharedPreferences(Robolectric.application.getApplicationContext());
     sharedPrefs.edit().putString("userName", "user1").commit();

     // Create the activity - this will call onCreate()
     activity=actController.create().get();
     loginButton=(Button)activity.findViewById(R.id.loginButton);
     userName=(EditText)activity.findViewById(R.id.userName);
     userPassword=(EditText)activity.findViewById(R.id.userPassword);

     // Verify text
     assertThat(userName.getText().toString(),equalTo("user1"));

}
Nachi
  • 4,218
  • 2
  • 37
  • 58