I finally solved my Compose testing problems, after spending quite some time trying to track down some very obscure bugs!
With Compose, when testing screens, you call
composeTestRule.setContent { MyScreen() }
- if you’ve written Compose UI tests, you’d be familiar with this.
If you need to run the tests against a particular activity, for some reason, you can use
androidComposeTestRule<MyActivity>
In my case,
MyActivity
calls
setContent { MyScreen() }
during
onCreate()
.
So, what ends up happening, is the test instantiates
MyActivity
, which calls
setContent()
, and the screen is composed, with its ViewModel and various dependencies. While this is happening, the test calls its own
setContent()
and the screen is composed again, in parallel! This causes all kinds of nightmarish problems.
tl;dr
Make sure when testing Compose, that you only call
setContent()
once per test. And be careful about which
Activity
you use to host the test, if you need one!