https://kotlinlang.org logo
#mockk
Title
# mockk
g

Gil Goldzweig

12/02/2021, 12:02 AM
Hi everyone, I have a really weird bug and I have no idea why. I'm trying to unit test changing android night theme so I'm using
mockkStatic
to mock
AppCompatDelegate
and it works well. I use the same function to test all 3 themes
Copy code
private fun testTheme(themeMode: Int, radioButtonId: Int) {
    System.out.println("Testing theme: $themeMode")
    selectedTheme = slot()
    every {
        setDefaultNightMode(capture(selectedTheme))
    } answers {
        System.out.println("Setting theme: ${selectedTheme.captured}")
    }

    onView(withId(radioButtonId)).perform(ViewActions.click())

    assertEquals(themeMode, selectedTheme.captured, "Selected theme")
    assertEquals(themeMode, selectedMode, "SharedPreferences")
}
Copy code
public static final int MODE_NIGHT_FOLLOW_SYSTEM = -1;
Copy code
public static final int MODE_NIGHT_NO = 1;
Copy code
public static final int MODE_NIGHT_YES = 2;
The
RadioButton
is just to select the right theme and call the check. These are the test cases
Copy code
@Test
fun `test clicking on light radio button applies light theme`() {
    initialize {
        testTheme(MODE_NIGHT_NO, R.id.fragment_theme_selection_radio_button_light)
    }
}

@Test
fun `test clicking on dark radio button applies dark theme`() {
    initialize {
        testTheme(MODE_NIGHT_YES, R.id.fragment_theme_selection_radio_button_dark)
    }
}

@Test
fun `test clicking on follow system radio button applies system theme`() {
    initialize {
        testTheme(MODE_NIGHT_FOLLOW_SYSTEM, R.id.fragment_theme_selection_radio_button_system)
    }
}
The function works for
NIGHT_NO
and
NIGHT_YES
but not in
FOLLOW_SYSTEM
It's not that I'm getting wrong values is that I received an exception
Copy code
lateinit property captured has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property captured has not been initialized
	at io.mockk.CapturingSlot.getCaptured(API.kt:2503)
But if I'll add any of the other tests first, it works
Copy code
@Test
fun `test clicking on follow system radio button applies system theme`() {
    initialize {
        testTheme(MODE_NIGHT_YES, R.id.fragment_theme_selection_radio_button_dark)
        testTheme(MODE_NIGHT_FOLLOW_SYSTEM, R.id.fragment_theme_selection_radio_button_system)
    }
}
Now, I tried to debug it, I'm unable to even capture it
m

Mattia Tommasone

12/02/2021, 8:41 AM
what if you call
testTheme
outside of
initialize
blocks?
g

Gil Goldzweig

12/02/2021, 4:56 PM
I can't I need it to setup the fragment code
74 Views