Roboelectric断言与Android共享偏好设置失败

3

参考这个SO问题,我尝试保存共享偏好,但我的断言失败了。

这是我的测试类:

@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"));

}

这是被测试类中的代码-
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);
        }
}

断言失败,提示预期值为"user1",但实际值为""

1个回答

3

您的测试首先创建了活动(并过早地触发了onCreate()),因此对共享偏好的更改没有效果。请尝试以下方法:

@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"));

}

谢谢,我刚刚要做这个,看到有人已经回答了 :)。 - inquisitive

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接