Robolectric usage

AndroidUiTesting includes some special ActivityScenarioConfigurators and FragmentScenarioConfigurators that are additionally safe-thread, what allows to run unit tests in parallel without unexpected behaviours.

Check out some examples below. It uses Roborazzi as screenshot testing library.

Activity

Here is with Junit4 test rule

@RunWith(RobolectricTestRunner::class) // or ParameterizedRobolectricTestRunner for parameterized test
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class SnapActivityTest {

    @get:Rule
    val robolectricScreenshotRule =
        robolectricActivityScenarioForActivityRule(
            config = ActivityConfigItem(
                systemLocale = "en",
                uiMode = UiMode.NIGHT,
                theme = R.style.Custom_Theme,
                orientation = Orientation.PORTRAIT,
                fontSize = FontSize.NORMAL,
                displaySize = DisplaySize.NORMAL,
                fontWeight = FontWeight.BOLD,
            ),
            deviceScreen = DeviceScreen.Phone.PIXEL_4A,
        )

    @Config(sdk = [30]) // Do not use qualifiers if using `DeviceScreen` in the Rule
    @Test
    fun snapActivity() {
        robolectricScreenshotRule
            .rootView
            .captureRoboImage("path/MyActivity.png")
    }
}

or without Junit4 test rules

Fragment

Here is with Junit4 test rule

or without Junit4 test rules

Android View

Here is with Junit4 test rule

or without Junit4 test rules

Jetpack Compose

Here is with RobolectricActivityScenarioForComposableRule test rule

The snapComposable method can be simplified further if adding the following dependency

and then capture image like this

You can also use AndroidUiTestingUtils without RobolectricActivityScenarioForComposableRule test rule as follows

Multiple Devices & Configs combined

AndroidUiTestingUtils also helps generate all parameters of a set of UiStates under a given set of devices and configurations. For that, use the corresponding type depending on what you are testing:

  • Activity: TestDataForActivity<MyEnum>

  • Fragment: TestDataForFragment<MyEnum>

  • Composable: TestDataForComposable<MyEnum>

  • View (e.g. Dialogs, ViewHolders): TestDataForView<MyEnum>

Here is an example with Views

Last updated