我有一个首选项 util 类,用于在单个位置存储和检索共享首选项中的数据。
Prefutils.java:
public class PrefUtils {
private static final String PREF_ORGANIZATION = "organization";
private static SharedPreferences getPrefs(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
private static SharedPreferences.Editor getEditor(Context context) {
return getPrefs(context).edit();
}
public static void storeOrganization(@NonNull Context context,
@NonNull Organization organization) {
String json = new Gson().toJson(organization);
getEditor(context).putString(PREF_ORGANIZATION, json).apply();
}
@Nullable public static Organization getOrganization(@NonNull Context context) {
String json = getPrefs(context).getString(PREF_ORGANIZATION, null);
return new Gson().fromJson(json, Organization.class);
}
}
显示 LoginActivity.java 中 PrefUtils 用法的示例代码:
@Override public void showLoginView() {
Organization organization = PrefUtils.getOrganization(mActivity);
mOrganizationNameTextView.setText(organization.getName());
}
build.gradle 中的 androidTestCompile
依赖项列表:
// Espresso UI Testing dependencies.
androidTestCompile "com.android.support.test.espresso:espresso-core:$project.ext.espressoVersion"
androidTestCompile "com.android.support.test.espresso:espresso-contrib:$project.ext.espressoVersion"
androidTestCompile "com.android.support.test.espresso:espresso-intents:$project.ext.espressoVersion"
androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2:'
src/androidTest/../LoginScreenTest.java
@RunWith(AndroidJUnit4.class) @LargeTest public class LoginScreenTest {
@Rule public ActivityTestRule<LoginActivity> mActivityTestRule =
new ActivityTestRule<>(LoginActivity.class);
@Before public void setUp() throws Exception {
when(PrefUtils.getOrganization(any()))
.thenReturn(HelperUtils.getFakeOrganization());
}
}
上面返回fakeOrganization
的代码不起作用,在登录 Activity 上运行测试会导致mOrganizationNameTextView.setText(organization.getName());
定义的行中出现NullPointerException在上面的LoginActivity.java类中。
如何解决上述问题?
最佳答案
方法 1:
使用 Dagger2 将 SharedPreference
公开到应用程序范围,并像在 Activity/fragment 中的 @Inject SharedPreferences mPreferences
一样使用它。
使用上述方法保存(写入)自定义首选项的示例代码:
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(PREF_ORGANIZATION, mGson.toJson(organization));
editor.apply();
要读取自定义首选项:
String organizationString = mPreferences.getString(PREF_ORGANIZATION, null);
if (organizationString != null) {
return mGson.fromJson(organizationString, Organization.class);
}
如果你像上面那样使用它,就会破坏 DRY 原则,因为代码会在多个地方重复。
<小时/>方法 2:
此方法基于这样的想法:拥有一个单独的首选项类,例如 StringPreference
/BooleanPreference
,它提供 SharedPreferences 代码的包装器来保存和检索值。
在继续解决方案之前,请阅读以下帖子以了解详细想法:
- Persist your data elegantly: U2020 way作者:@tasomaniac
- Espresso 2.1: ActivityTestRule作者: 千纪
- Dagger 2 + Espresso 2 + Mockito
代码:
ApplicationModule.java
@Module public class ApplicationModule {
private final MyApplication mApplication;
public ApplicationModule(MyApplication application) {
mApplication = application;
}
@Provides @Singleton public Application provideApplication() {
return mApplication;
}
}
DataModule.java
@Module(includes = ApplicationModule.class) public class DataModule {
@Provides @Singleton public SharedPreferences provideSharedPreferences(Application app) {
return PreferenceManager.getDefaultSharedPreferences(app);
}
}
GsonModule.java
@Module public class GsonModule {
@Provides @Singleton public Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
}
ApplicationComponent.java
@Singleton @Component(
modules = {
ApplicationModule.class, DataModule.class, GsonModule.class
}) public interface ApplicationComponent {
Application getMyApplication();
SharedPreferences getSharedPreferences();
Gson getGson();
}
MyApplication.java
public class MyApplication extends Application {
@Override public void onCreate() {
initializeInjector();
}
protected void initializeInjector() {
mApplicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
}
OrganizationPreference.java
public class OrganizationPreference {
public static final String PREF_ORGANIZATION = "pref_organization";
SharedPreferences mPreferences;
Gson mGson;
@Inject public OrganizationPreference(SharedPreferences preferences, Gson gson) {
mPreferences = preferences;
mGson = gson;
}
@Nullable public Organization getOrganization() {
String organizationString = mPreferences.getString(PREF_ORGANIZATION, null);
if (organizationString != null) {
return mGson.fromJson(organizationString, Organization.class);
}
return null;
}
public void saveOrganization(Organization organization) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(PREF_ORGANIZATION, mGson.toJson(organization));
editor.apply();
}
}
无论您在哪里需要首选项,只需使用 Dagger @Inject OrganizationPreference mOrganizationPreference;
注入(inject)它即可。
对于androidTest
,我用模拟首选项覆盖首选项。以下是我的 android 测试配置:
TestDataModule.java
public class TestDataModule extends DataModule {
@Override public SharedPreferences provideSharedPreferences(Application app) {
return Mockito.mock(SharedPreferences.class);
}
}
MockApplication.java
public class MockApplication extends MyApplication {
@Override protected void initializeInjector() {
mApplicationComponent = DaggerTestApplicationComponent.builder()
.applicationModule(new TestApplicationModule(this))
.dataModule(new TestDataModule())
.build();
}
}
LoginScreenTest.java
@RunWith(AndroidJUnit4.class) public class LoginScreenTest {
@Rule public ActivityTestRule<LoginActivity> mActivityTestRule =
new ActivityTestRule<>(LoginActivity.class, true, false);
@Inject SharedPreferences mSharedPreferences;
@Inject Gson mGson;
@Before public void setUp() {
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
MyApplication app = (MyApplication) instrumentation.getTargetContext().getApplicationContext();
TestApplicationComponent component = (TestApplicationComponent) app.getAppComponent();
component.inject(this);
when(mSharedPreferences.getString(eq(OrganizationPreference.PREF_ORGANIZATION),
anyString())).thenReturn(mGson.toJson(HelperUtils.getFakeOrganization()));
mActivityTestRule.launchActivity(new Intent());
}
}
确保您在 build.gradle 中添加了 dexmaker mockito
androidTestCompile 'com.google.dexmaker:dexmaker:1.2'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.2:'
关于android - 如何模拟 Android 仪器测试的共享首选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38154140/