Skip to content

Commit

Permalink
test: improve 'getLatestAlertDialog' error
Browse files Browse the repository at this point in the history
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 <null>
```

Seen in https://redirect.github.com/ankidroid/Anki-Android/pull/16529
  • Loading branch information
david-allison committed Jun 4, 2024
1 parent 812fd2c commit f2cca93
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions AnkiDroid/src/test/java/com/ichi2/anki/RobolectricTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -480,3 +481,6 @@ open class RobolectricTest : AndroidTest {
}
}
}

private fun getLatestAlertDialog(): AlertDialog =
assertNotNull(ShadowDialog.getLatestDialog() as? AlertDialog, "A dialog should be displayed")

0 comments on commit f2cca93

Please sign in to comment.