【发布时间】:2012-06-30 02:39:05
【问题描述】:
我是使用 Robotium 的新手,似乎在任何地方的论坛上都找不到任何答案。我有一个要测试的 PreferenceActivity。问题是每当我需要单击首选项时,我的单元测试都会失败。
更具体地说,我有一个 CheckBoxPreference 我正在运行一些测试。我想验证当 CheckBoxPreference 被选中时,屏幕上有某些首选项已启用(未变灰),反之亦然。截至目前,我什至无法使用 searchText()/waitForText() 方法找到偏好(这是屏幕上的第一个偏好)。在从getView() 获得偏好视图后,我也尝试使用clickOnView() 方法。
似乎我现在能做的最好的事情就是使用 Android 的 setChecked() 方法来操纵 CheckBoxPreference 的状态。我假设以这种方式进行测试是可能的,但是我正在研究一些基本的东西。由于PreferenceActivity也是ListActivity,所以我也尝试搜索过测试ListActivity的相关问题,无济于事。
以下几个链接让我有了使用 PreferenceActivities 和 Robotium 的良好开端。
这是我正在使用的代码:
public void testEnabledChecked() throws Exception {
CheckBoxPreference enabled = PrefTestingUtils.getCheckBoxPreference(mSolo, mActivity,
(String) getVal("KEY_ENABLED"));
EditTextPreference recipient = PrefTestingUtils.getEditTextPreference(mSolo, mActivity,
(String) getVal("KEY_RECIPIENT"));
EditTextPreference title = PrefTestingUtils.getEditTextPreference(mSolo, mActivity,
(String) getVal("KEY_TITLE"));
ListPreference interval = PrefTestingUtils.getListPreference(mSolo, mActivity,
(String) getVal("KEY_INTERVAL"));
// ensures that the preference is unchecked
if (!enabled.isChecked()) {
Log.d(TAG, "Enabled preference unchecked, clicking on it");
// mSolo.clickOnView(enabled.getView(null, null)); // Attempt #1
// mSolo.clickOnText("Enabled"); // Attempt #2
// mSolo.clickOnCheckBox(0); // Attempt #3
// mSolo.searchText("Enabled"); // cannot find view
}
assertTrue(enabled.isChecked()); // AssertionFailedError here
assertTrue(recipient.isEnabled());
assertTrue(title.isEnabled());
assertTrue(interval.isEnabled());
}
我已经验证 PrefTestingUtils 函数确实返回了对首选项的有效引用。 PrefTestingUtils 的所有函数都与此类似:
public static CheckBoxPreference getCheckBoxPreference(Solo solo,
PreferenceActivity activity, String key) {
if (solo == null || activity == null || key == null) {
Log.d(TAG, "getCheckBoxPreference::Null parameter");
return null;
}
Preference p = activity.findPreference(key);
if (p instanceof CheckBoxPreference) {
return (CheckBoxPreference) p;
}
return null;
}
任何人都可以提供任何帮助将不胜感激。谢谢!
【问题讨论】:
-
我之前已经成功测试过一个 PreferenceActivity。你试过什么?你应该发布你当前的测试类代码,否则很难给你指点。
-
谢谢,dmon。我已经编辑了我的帖子以包含我的代码。
标签: android unit-testing robotium