From f2cca9332b862d4b642ab5566984f37fedb8f582 Mon Sep 17 00:00:00 2001 From: David Allison <62114487+david-allison@users.noreply.github.com> Date: Tue, 4 Jun 2024 12:53:26 +0100 Subject: [PATCH] test: improve 'getLatestAlertDialog' error Previously this resulted in a `NullPointerException` before: ``` java.lang.NullPointerException: null cannot be cast to non-null type androidx.appcompat.app.AlertDialog ``` after: ``` org.opentest4j.AssertionFailedError: A dialog should be displayed ==> expected: not ``` Seen in https://redirect.github.com/ankidroid/Anki-Android/pull/16529 --- AnkiDroid/src/test/java/com/ichi2/anki/RobolectricTest.kt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/AnkiDroid/src/test/java/com/ichi2/anki/RobolectricTest.kt b/AnkiDroid/src/test/java/com/ichi2/anki/RobolectricTest.kt index 17a6d2e052d8..42f65cce7587 100644 --- a/AnkiDroid/src/test/java/com/ichi2/anki/RobolectricTest.kt +++ b/AnkiDroid/src/test/java/com/ichi2/anki/RobolectricTest.kt @@ -65,6 +65,7 @@ import org.robolectric.shadows.ShadowLog import org.robolectric.shadows.ShadowLooper import org.robolectric.shadows.ShadowMediaPlayer import timber.log.Timber +import kotlin.test.assertNotNull open class RobolectricTest : AndroidTest { @@ -197,7 +198,7 @@ open class RobolectricTest : AndroidTest { * Click on a dialog button for an AlertDialog dialog box. Replaces the above helper. */ protected fun clickAlertDialogButton(button: Int, @Suppress("SameParameterValue") checkDismissed: Boolean) { - val dialog = ShadowDialog.getLatestDialog() as AlertDialog + val dialog = getLatestAlertDialog() dialog.getButton(button).performClick() // Need to run UI thread tasks to actually run the onClickHandler @@ -216,7 +217,7 @@ open class RobolectricTest : AndroidTest { * TODO: Rename to getDialogText when all MaterialDialogs are changed to AlertDialogs */ protected fun getAlertDialogText(@Suppress("SameParameterValue") checkDismissed: Boolean): String? { - val dialog = ShadowDialog.getLatestDialog() as AlertDialog + val dialog = getLatestAlertDialog() if (checkDismissed && Shadows.shadowOf(dialog).hasBeenDismissed()) { Timber.e("The latest dialog has already been dismissed.") return null @@ -480,3 +481,6 @@ open class RobolectricTest : AndroidTest { } } } + +private fun getLatestAlertDialog(): AlertDialog = + assertNotNull(ShadowDialog.getLatestDialog() as? AlertDialog, "A dialog should be displayed")