I am trying to build unit-test case for a custom dialog that extends the Android DialogFragment using Roboletric but I hit a hard wall. Basically, the unit-test framework cannot make the fragment "visible"; therefore, I cannot test anything.
anyway, the code is pretty basic and based on this thread:
How to create a Custom Dialog box in android?
here's is my app code:
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;
}
}
the super basic custom layout
<?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>
Finally my unit-test:
@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);
}
It always asserts saying it is not visible :( Yet, the code works fine on the device.
Here are the relevant parts in the 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'
}
Anyone can help me? I am totally stuck on the most basic functionally for the unit-test.
thank you!