我刚开始学习Android测试,这让我发疯。该功能正常,但我无法运行我的测试。我试图从SharedPreferences
读取一个值,并将其与TextView的内容进行比较。我在Android Studio 2.3.3上使用Espresso。
此行String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne));
会导致此android.content.res.Resources$NotFoundException: String resource ID #0x7f09004d
例外。这与我在片段中用于访问共享首选项的代码基本相同。
我找不到任何引用同样问题的东西。我觉得我只是有一个简单的配置错误,但我无法弄明白。提前致谢。
这是我的整个测试:
@Test
public void setsPlayerNamesFromSettings(){
Context context = getInstrumentation().getContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String player1Name = sharedPreferences.getString(context.getString(R.string.KEYplayerOneDefaultNameSetting), context.getString(R.string.playerOne));
onView(withId(R.id.LpCalculatorTextPlayer1Name)).check(matches(withText(player1Name)));
String player2Name = sharedPreferences.getString(context.getString(R.string.KEYplayerTwoDefaultNameSetting), context.getString(R.string.playerTwo));
onView(withId(R.id.LpCalculatorTextPlayer2Name)).check(matches(withText(player2Name)));
}
如果有任何帮助,请参阅我的Fragment中访问SharedPreferences的代码
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
mLpCalculatorModel.setLpDefault(Integer.parseInt(preferences.getString(getString(R.string.KEYdefaultLpSetting), "8000")));
mLpCalculatorModel.setPlayer1Name(preferences.getString(getString(R.string.KEYplayerOneDefaultNameSetting), getString(R.string.playerOne)));
mLpCalculatorModel.setPlayer2Name(preferences.getString(getString(R.string.KEYplayerTwoDefaultNameSetting), getString(R.string.playerTwo)));
mLpCalculatorModel.setAllowsNegativeLp(preferences.getBoolean(getString(R.string.KEYallowNegativeLp), false));
tvPlayer1Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
tvPlayer2Lp.setText(Integer.toString(mLpCalculatorModel.getLpDefault()));
答案 0 :(得分:2)
getInstrumentation().getContext()
这会返回代表您的Context
来源集的androidTest
。如果您的资源位于其他位置(例如main
),请使用:
getInstrumentation().getTargetContext()