Skip to content

Instantly share code, notes, and snippets.

@jfresen
Last active July 10, 2024 08:47
Show Gist options
  • Save jfresen/44f3838fbd00e3c4342c7be4c9a4e6f7 to your computer and use it in GitHub Desktop.
Save jfresen/44f3838fbd00e3c4342c7be4c9a4e6f7 to your computer and use it in GitHub Desktop.
Logs all state changes so you can find out what causes a self-invalidating loop in your app in case you keep running into timeouts in your tests
// Use this template if you use ComposeTestRule (createComposeRule())
// Use the other template if you use ComposeUiTest (runComposeUiTest())
private val TAG = "TEST_TAG"
private var I = 0 // add a sequence number to every log message for disambiguation
private var unregisterApplyObserver: ObserverHandle? = null
@Test
fun test() {
// your test here
}
@Before
fun setup() {
unregisterApplyObserver = Snapshot.registerApplyObserver { mutatedObjects, snapshot ->
Log.i(TAG, "[${I++}] applying snapshot")
for (obj in mutatedObjects) {
Log.d(TAG, "[${I++}] object $obj modified")
}
}
}
@After
fun tearDown() {
unregisterApplyObserver?.dispose()
}
// Use this template if you use ComposeUiTest (runComposeUiTest())
// Use the other template if you use ComposeTestRule (createComposeRule())
private val TAG = "TEST_TAG"
private var I = 0 // add a sequence number to every log message for disambiguation
@Test
fun test() = runComposeUiTest {
withApplyObserver {
// your test here
}
}
private inline fun withApplyObserver(block: () -> Any) {
var unregisterApplyObserver: ObserverHandle? = null
try {
unregisterApplyObserver = Snapshot.registerApplyObserver { mutatedObjects, snapshot ->
Log.i(TAG, "[${I++}] applying snapshot")
for (obj in mutatedObjects) {
Log.d(TAG, "[${I++}] object $obj modified")
}
}
block()
} finally {
unregisterApplyObserver?.dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment