引用此SO question,我尝试保存共享首选项,但我的断言失败了。
这是我的测试类
@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);
}
}
Assertion
失败,它说预期"user1"
但找到""
。
答案 0 :(得分:3)
您的测试是首先创建活动(并过早触发onCreate()
),因此您对SharedPrefs的更改无效。试试这个:
@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"));
}