如何在android中为actionbar项编写junit测试用例?有什么方法可以获得对其执行点击事件的参考吗?
答案 0 :(得分:3)
您可以模拟单击ActionBar项目,如下所示:
public void testButton(){
final View view = activity.findViewById(com.example.R.id.button1);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
view.requestFocus();
view.callOnClick();
}
});
}
答案 1 :(得分:1)
在下面的示例中,我可以检索操作栏的导航选项卡按钮(native或ActionBarSherlock)。然后我用TouchUtils.clickView()点击它们:
try {
// Trying to get the ActionBar view '@id/android:action_bar_container' dynamically
int resId =
a.getResources().getIdentifier("action_bar_container", "id", "android");
View actionBarContainer = a.findViewById(resId);
// The class 'com.android.internal.widget.ActionBarContainer' must be in
// the classpath of this test project to be able to call
// the method 'getTabContainer' at runtime
Method getTabContainer =
com.android.internal.widget.ActionBarContainer.class.getMethod("getTabContainer",
(Class<?>[]) null);
HorizontalScrollView tabContainer =
(HorizontalScrollView) getTabContainer.invoke(actionBarContainer, (Object[]) null);
return ((ViewGroup) tabContainer.getChildAt(0)).getChildAt(tabIndex);
} catch (Exception e) {
// Trying with SherlockActionBar
com.actionbarsherlock.internal.widget.ActionBarContainer actionBarContainer =
(com.actionbarsherlock...) a.findViewById(R.id.abs__action_bar_container);
HorizontalScrollView tabContainer =
(HorizontalScrollView) actionBarContainer.getTabContainer();
return ((ViewGroup) tabContainer.getChildAt(0)).getChildAt(tabIndex);
}
}
答案 2 :(得分:1)
使用robotium.jar库
import com.jayway.android.robotium.solo.Solo;
private Solo solo;
this.solo = new Solo(getInstrumentation(),getActivity());
//R.id.menu_action_signup Menu Iten id.
this.solo.clickOnView(this.solo.getView(R.id.menu_action_signup));
答案 3 :(得分:0)
我通过创建自己的自定义MenuItem类并手动调用Activity的onOptionsItemSelected(MenuItem项)来解决。 为Junit测试做任何其他正确的方法吗?
答案 4 :(得分:0)
我正在使用ActionBarSherlock提供的ActionBar并遇到了这个问题。我发现这样做的最好方法是:
在您的测试用例中,您需要对Instrumentation和菜单的引用,允许您通过id选择MenuItem:
private void clickOnMenuItem(int menuItemId, Instrumentation instruments, Menu menuInstance) {
final Integer itemId = menuItemId;
final Menu menu = menuInstance;
instruments.runOnMainSync(new Runnable() {
@Override
public void run() {
menu.performIdentifierAction(itemId, 0);
}
});
}