gpt4 book ai didi

android - Robolectric 断言因共享首选项 android 而失败

转载 作者:太空狗 更新时间:2023-10-29 12:41:01 25 4
gpt4 key购买 nike

引用此 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);
}
}

断言 失败,它说预期的 "user1" 但找到了 ""

最佳答案

您的测试首先创建 Activity (并且过早触发 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"));

}

关于android - Robolectric 断言因共享首选项 android 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25787289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com