[FIXED] Test error:MyActivity has already set content. If you have populated the Activity with a ComposeView, make sure to call setContent on that ComposeView

Issue

When running Robolectric unit tests with the latest version of Compose 1.2.0, then the tests using createAndroidComposeRule fail with the following error:

MyActivity has already set content. If you have populated the Activity with a ComposeView, make sure to call setContent on that ComposeView instead of on the test rule; and make sure that that call to setContent {} is done after the ComposeTestRule has run

Code from one of the failing tests:

composeTestRule.setContent {
    Column {
        Text(textTitle)
        DemoScopedInjectedViewModelComposable()
    }
}

Solution

Looking carefully, the error message helps a lot, even though it’s talking about a ComposeView instead of an Activity. But according to it:

composeTestRule.setContent { ... }

should be changed to:

composeTestRule.activity.setContent { ... }

and the tests should run without this error occurring anymore.

Answered By – coroutineDispatcher

Answer Checked By – Timothy Miller (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published