使用Robolectric进行DialogFragment测试

6

我希望测试一个dialog Fragment是否在使用Roboelectric时显示出来。

public class SomeDialogActivity extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        DialogFragment someDialogFragment = new SomeDialogFragment();
        someDialogFragment.show(getSupportFragmentManager(), "some_dialog");
    }
}

现在我想测试一下是否会出现这个对话框,就像这样:
@Test
public void dialogFragmentIsShownToTheUser() {
        DialogFragment dialog = new SomeDialogFragment();
        DialogFragment someDialogFragment = new SomeDialogFragment();
        startFragment(someDialogFragment);

        SomeDialogActivity activity = Robolectric.setupActivity(SomeDialogActivity.class);

        Dialog dialog = ShadowDialog.getLatestDialog();
        assertNotNull(dialog);
        assertEquals(.... , ....)
}
1个回答

4

将其视为常规的片段情况。因此,要检查片段是否显示,您需要编写以下代码:

@Test
public void dialogFragmentIsShownToTheUser() {
    SomeDialogActivity activity = Robolectric.setupActivity(SomeDialogActivity.class);

    DialogFragment dialogFragment = (DialogFragment) activity.getSupporFragmetManager()
                                       .findFragmentByTag("some_dialog");
    assertNotNull(dialogFragment);
}

问题在于,一旦DialogFragment被初始化,它就不会回到assertNotNull检查。它被卡住了,我得到了这个错误。android.content.res.Resources$NotFoundException: 无法找到资源ID#0x7f030023... android.content.res.Resources.loadXmlResourceParser(Resources.java) at android.content.res.Resources.getLayout(Resources.java:852) at android.view.LayoutInflater.inflate(LayoutInflater.java:394) at android.view.LayoutInflater.inflate(LayoutInflater.java:352) at com.xxx.yyy.zzz.fragments.MacDialogFragment.onCreateDialog(MacDialogFragment.java:36) ..... - Pranav Kotecha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接