如何使用Robolectric,RoboGuice,ABS测试ActionProvider.onCreateAction



我有一个ActionProvider,我想测试onCreateActionView方法。当我从测试中调用此方法时,出现以下异常:

java.lang.AssertionError: LayoutInflater not found.
at android.view.LayoutInflater.from(LayoutInflater.java:214)
at android.view.View.inflate(View.java:16803)
at com.my.app.actionprovider.ContentTypeActionProvider.onCreateActionView(ContentTypeActionProvider.java:58)

这是方法:

@Override
public View onCreateActionView() {

    view = View.inflate(context, R.layout.layout_actionbarpopupmenu, null);
    textView = (TextView) view.findViewById(R.id.description);
    menu = new PopupMenu(context, view);

    int order = 1;
    if(ESA){
        SubMenu submenu = null;
        for (ContentType contentType : ContentType.values()) {
            if (contentType.isFirstInGroup()) {
                submenu = menu.getMenu().addSubMenu(-1, -1, order++, contentType.getGroupName());
                submenu.setIcon(context.getResources().getDrawable(R.drawable.down_arrow));
                submenu.add(contentType.getGroupId(), contentType.getId(), order++, contentType.getName());
            } else if (contentType.isGroup()) {
                submenu.add(contentType.getGroupId(), contentType.getId(), order++, contentType.getName());
            } else {
                menu.getMenu().add(contentType.getGroupId(), contentType.getId(), order++, contentType.getName());
            }
        }
    }
    else{        
        for (ContentType contentType : contentTypeHelper.getContentTypes()) {
            menu.getMenu().add(contentType.getGroupId(), contentType.getId(), order++, contentType.getName());
        }
    }
    UIHelper.setIconVisibleOnMenu(menu);
    menu.setOnMenuItemClickListener(this);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menu.show();
        }
    });
    setDefaultOption();
    return view;
}

有没有办法测试这种方法?

您收到该错误是因为您使用的上下文不正确,要使其正常工作,您可以使用:

RuntimeEnvironment.context

作为模拟上下文,如果您使用 Robolectric 进行测试。

最新更新