4

What is the best way to test the different DayNight themes on Android using Espresso? (or something better?) I haven't found anything on the internet. I thought this must be something big because of everything migrating to DayNight now.

I want to know things like: "when I click this button, has my activity theme changed" or "I have this background and this text, is the contrast right".

Thanks in advance.

Andre Thiele
  • 3,202
  • 3
  • 20
  • 43
  • 1
    One aspect of the problem is programmatically determining from Espresso code whether dark mode is turned on in the operating system settings. For that, you can determine the dark mode status using `context?.resources?.configuration?.uiMode` (source: https://stackoverflow.com/questions/44170028/android-how-to-detect-if-night-mode-is-on-when-using-appcompatdelegate-mode-ni). – Michael Osofsky Jul 01 '20 at 20:44

1 Answers1

3

I have found this to work:

    @get:Rule
    val activityTestRule = ActivityScenarioRule(...Activity::class.java)

    private fun createActivityScenarioRule(withNightMode: Boolean = false) =
        activityTestRule.scenario.apply {
            onActivity {
                AppCompatDelegate.setDefaultNightMode(
                    if (withNightMode) AppCompatDelegate.MODE_NIGHT_YES
                    else AppCompatDelegate.MODE_NIGHT_NO
                )
            }
        }
Quintin Balsdon
  • 5,484
  • 10
  • 54
  • 95