Skip to content

Instantly share code, notes, and snippets.

@jfresen
Last active October 2, 2024 15:50
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
private var unregisterWriteObserver: ObserverHandle? = null
@Test
fun test() {
// your test here
}
@Before
fun setup() {
unregisterApplyObserver = Snapshot.registerApplyObserver { mutatedObjects, snapshot ->
val colon = if (mutatedObjects.isNotEmpty()) ":" else ""
Log.i(TAG, "[${I++}] applying snapshot$colon")
for (obj in mutatedObjects) {
Log.d(TAG, "[${I++}] modified: $obj")
}
}
unregisterWriteObserver = Snapshot.registerGlobalWriteObserver { mutatedObject ->
Log.d(TAG, "[${I++}] writing in snapshot: $mutatedObject")
}
}
@After
fun tearDown() {
unregisterApplyObserver?.dispose()
unregisterWriteObserver?.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 {
withApplyAndWriteObserver {
// your test here
}
}
private inline fun withApplyAndWriteObserver(block: () -> Any) {
var unregisterApplyObserver: ObserverHandle? = null
var unregisterWriteObserver: ObserverHandle? = null
try {
unregisterApplyObserver = Snapshot.registerApplyObserver { mutatedObjects, snapshot ->
Log.i(TAG, "[${I++}] applying snapshot")
for (obj in mutatedObjects) {
Log.d(TAG, "[${I++}] modified: $obj")
}
}
unregisterWriteObserver = Snapshot.registerGlobalWriteObserver { mutatedObject ->
Log.d(TAG, "[${I++}] writing in snapshot: $mutatedObject")
}
block()
} finally {
unregisterApplyObserver?.dispose()
unregisterWriteObserver?.dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment