Robolectric 无法使自定义对话框可见

Roboletric can't make custom dialog visible

我正在尝试为使用 Roboletric 扩展 Android DialogFragment 的自定义对话框构建单元测试用例,但我遇到了困难。基本上,单元测试框架无法制作片段"visible";因此,我无法测试任何东西。

无论如何,代码非常基础并且基于此线程:

How to create a Custom Dialog box in android?

这是我的应用程序代码:

public class CustomDialog extends DialogFragment {
    public Dialog mCustomDialogTest;
    public EditText mEditText;
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mCustomDialogTest = new Dialog(getActivity());
        mCustomDialogTest.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        mCustomDialogTest.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        mCustomDialogTest.setContentView(R.layout.custom_dialog);
        mCustomDialogTest.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mEditText = (EditText) mCustomDialogTest.findViewById(R.id.edit_text_id);
        return mCustomDialogTest;
    }
}

超级基本的自定义布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <EditText
        android:id="@+id/edit_text_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:hint="@string/app_name"
        android:inputType="text" />
</LinearLayout>

最后是我的单元测试:

@Test
public void testCustomDialog() {
    CustomDialog customDialog = new CustomDialog();
    customDialog.show(mActivity.getFragmentManager(), getClass().getName());

    boolean visible = customDialog.isVisible(); //This never works :(
    Assert.assertTrue("Dialog is visible", visible);
}

它总是断言说它不可见 :( 然而,代码在设备上运行良好。

以下是gradle中的相关部分:

    testOptions {
        unitTests {
            includeAndroidResources = true
        }
    }

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    testImplementation 'androidx.test.espresso:espresso-core:3.1.0'
    testImplementation 'androidx.test:core:1.0.0'
    testImplementation 'androidx.test.ext:junit:1.0.0'
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.mockito:mockito-core:2.23.0'
    testImplementation 'org.robolectric:robolectric:4.0.2'
    androidTestImplementation 'com.google.truth:truth:0.42'
    testImplementation 'com.google.truth:truth:0.42'
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
}

谁能帮帮我?我完全停留在单元测试的最基本功能上。

谢谢!

尝试使用 getUserVisibleHint 方法而不是 isVisible 方法