小编cla*_*o_n的帖子

测试需要父 Activity 实现侦听器的片段

我正在尝试使用 Robolectric 测试片段。该片段包含以下代码:

public class MyDialogFragment extends DialogFragment {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Verify that the host activity implements the callback interface
            try {
                // Instantiate the MyDialogListener so we can send events to the host
                this.setListener((MyDialogListener) getActivity());
            } catch (ClassCastException e) {
                throw new ClassCastException(getActivity().toString()
                        + " must implement MyDialogListener");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这种确保其所有者实现其侦听器的片段模式在 Android 中非常普遍。我目前正在我的 @Test 中创建我的片段和活动,如下所示:

fragment = MyDialogFragment.newInstance(/* Some params */);

FragmentActivity activity = Robolectric
        .buildActivity(FragmentActivity.class)
        .create().start()
        .resume().get();
shadowActivity = shadowOf(activity);

FragmentManager fragmentManager …
Run Code Online (Sandbox Code Playgroud)

java android unit-testing mockito robolectric

5
推荐指数
0
解决办法
1370
查看次数

标签 统计

android ×1

java ×1

mockito ×1

robolectric ×1

unit-testing ×1