testing-state-restoration
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTesting State Restoration — StateRestorationTester
Round-Trips Only rememberSaveable
StateRestorationTesterrememberSaveable测试状态恢复——StateRestorationTester
往返测试仅覆盖 rememberSaveable
StateRestorationTesterrememberSaveableStateRestorationTesterLocalSaveableStateRegistryApplication.onCreateStateRestorationTesterLocalSaveableStateRegistryApplication.onCreateWhen to use this skill
何时使用此 skill
- The developer is verifying that survives — for a
rememberSaveable, a TextField value, a screen toggle, etc.LazyListState - The developer asks "how do I test in a unit test?"
rememberSaveable - A test calls and the state appears unchanged or null.
emulateSavedInstanceStateRestore() - The developer hits .
IllegalStateException: Bundle exceeds maximum size (1 MB) - A reviewer asks for a regression test for a save/restore bug fix.
- 开发者正在验证 能否保留状态,例如
rememberSaveable、TextField 值或屏幕开关等。LazyListState - 开发者询问“如何在单元测试中测试 ?”
rememberSaveable - 测试调用了 ,但状态看起来没有变化或仍为 null。
emulateSavedInstanceStateRestore() - 开发者遇到 。
IllegalStateException: Bundle exceeds maximum size (1 MB) - 审查者要求为保存与恢复相关的缺陷修复添加回归测试。
When NOT to use this skill
何时不应使用此 skill
- The bug under test is an Activity recreation issue (rotation re-creates the Activity, callbacks fire, ViewModels rebind). does not exercise that path; use Espresso
StateRestorationTesterplus this skill if both phases need coverage.ActivityScenario.recreate() - The state is in a and the developer wants to test
ViewModel. Use the AndroidX ViewModel testing tools.SavedStateHandle - The class skeleton is wrong — fix first.
../structuring-a-compose-test/SKILL.md
- 待测试的缺陷涉及 Activity 重建(屏幕旋转会重新创建 Activity,回调会触发,ViewModel 会重新绑定)。不会覆盖该路径;如果两个阶段都需要测试,请使用 Espresso
StateRestorationTester并结合此 skill。ActivityScenario.recreate() - 状态位于 中,而开发者希望测试
ViewModel。请使用 AndroidX ViewModel 测试工具。SavedStateHandle - 测试类结构本身不正确——应先修复 。
../structuring-a-compose-test/SKILL.md
Prerequisites
前置条件
- on
androidx.compose.ui:ui-test-junit4.androidTestImplementationis in packageStateRestorationTester.androidx.compose.ui.test.junit4 - A (i.e. one of
ComposeContentTestRule/createComposeRule()).createAndroidComposeRule<A>()is NOT compatible because it returnscreateEmptyComposeRule(), which has noComposeTestRule.setContent - The Composable under test stores its state with (or registers via
rememberSaveable { … }). PlainSaveableStateRegistrydoes NOT survive the round-trip — the KDoc states it explicitly: "the state stored via regular state() or remember() will be lost." (cited atremember).compose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/StateRestorationTester.android.kt:67-68
- 在 中添加
androidTestImplementation。androidx.compose.ui:ui-test-junit4位于StateRestorationTester包中。androidx.compose.ui.test.junit4 - 需要一个 ,即
ComposeContentTestRule或createComposeRule()之一。createAndroidComposeRule<A>()不兼容,因为它返回的是没有createEmptyComposeRule()方法的setContent。ComposeTestRule - 被测 Composable 必须使用 保存状态(或通过
rememberSaveable { … }注册状态)。普通SaveableStateRegistry不会在往返过程中保留状态——KDoc 明确指出:“通过普通 state() 或 remember() 保存的状态将会丢失。”(引用自remember)。compose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/StateRestorationTester.android.kt:67-68
Workflow
工作流
- 1. Construct the tester from the rule.
kotlin
import androidx.compose.ui.test.junit4.StateRestorationTester
@get:Rule val rule = createComposeRule(StandardTestDispatcher())
val restorationTester = StateRestorationTester(rule)The constructor signature is , file .
class StateRestorationTester(private val composeTestRule: ComposeContentTestRule)StateRestorationTester.android.kt:43-
2. Useinstead of
restorationTester.setContent { }. This is non-negotiable: the tester replaces therule.setContent { }for the wrapped content. CallingLocalSaveableStateRegistrydirectly bypasses the injection andrule.setContentwill fail withemulateSavedInstanceStateRestore(cited at"setContent should be called first!").StateRestorationTester.android.kt:71 -
3. Hoist the state reference as a nullabledeclared above
var. This is the canonical shape — seesetContent:compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListTest.kt:890-913
kotlin
@Test
fun stateIsRestored() {
val restorationTester = StateRestorationTester(rule)
var state: LazyListState? = null
restorationTester.setContent {
state = rememberLazyListState()
LazyColumn(Modifier.requiredSize(100.dp).testTag(LazyListTag), state = state!!) {
items(20) { Spacer(Modifier.requiredSize(20.dp).testTag("$it")) }
}
}
rule.onNodeWithTag(LazyListTag).performScrollToIndex(2)
val (index, scrollOffset) = rule.runOnIdle {
state!!.firstVisibleItemIndex to state!!.firstVisibleItemScrollOffset
}
state = null // (*) clear the reference
restorationTester.emulateSavedInstanceStateRestore() // save → dispose → restore
rule.runOnIdle {
assertThat(state!!.firstVisibleItemIndex).isEqualTo(index)
assertThat(state!!.firstVisibleItemScrollOffset).isEqualTo(scrollOffset)
}
}-
4. Drive the state to a non-default value. A test that asserts a default cannot prove restoration occurred. Scroll the list, type into the TextField, toggle the switch.
-
5. Capture the values to compare against. Read the state insideand store them in
runOnIdle { }s.val -
6. Setbetween the capture and
state = null. This is the load-bearing trick. The first composition assigned a value toemulateSavedInstanceStateRestore(); nulling it forces the secondstateaccess to read whatever the second composition assigns — proving the second composition really happened. Without nulling, the test asserts on the original instance and would pass even if the round-trip silently restored nothing.state!! -
7. Call. The internal flow (cited at
emulateSavedInstanceStateRestore()) is threeStateRestorationTester.android.kt:70-77blocks:runOnIdle,saveStateAndDisposeChildren, then a no-op block to wait for emission.emitChildrenWithRestoredState -
8. Re-read the state insideand assert equality with the captured values.
runOnIdle
- 1. 使用 rule 构造测试器。
kotlin
import androidx.compose.ui.test.junit4.StateRestorationTester
@get:Rule val rule = createComposeRule(StandardTestDispatcher())
val restorationTester = StateRestorationTester(rule)构造器签名为 ,位于文件 。
class StateRestorationTester(private val composeTestRule: ComposeContentTestRule)StateRestorationTester.android.kt:43-
2. 使用,而不是
restorationTester.setContent { }。 这一点不可妥协:测试器会为被包装的内容替换rule.setContent { }。直接调用LocalSaveableStateRegistry会绕过注入,随后调用rule.setContent将因emulateSavedInstanceStateRestore而失败(引用自IllegalStateException("setContent should be called first!"))。StateRestorationTester.android.kt:71 -
3. 将状态引用提升为位于上方的 nullable
setContent。 这是规范写法——参见var:compose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListTest.kt:890-913
kotlin
@Test
fun stateIsRestored() {
val restorationTester = StateRestorationTester(rule)
var state: LazyListState? = null
restorationTester.setContent {
state = rememberLazyListState()
LazyColumn(Modifier.requiredSize(100.dp).testTag(LazyListTag), state = state!!) {
items(20) { Spacer(Modifier.requiredSize(20.dp).testTag("$it")) }
}
}
rule.onNodeWithTag(LazyListTag).performScrollToIndex(2)
val (index, scrollOffset) = rule.runOnIdle {
state!!.firstVisibleItemIndex to state!!.firstVisibleItemScrollOffset
}
state = null // (*) clear the reference
restorationTester.emulateSavedInstanceStateRestore() // save → dispose → restore
rule.runOnIdle {
assertThat(state!!.firstVisibleItemIndex).isEqualTo(index)
assertThat(state!!.firstVisibleItemScrollOffset).isEqualTo(scrollOffset)
}
}-
4. 将状态驱动至非默认值。 断言默认值的测试无法证明恢复确实发生。可以滚动列表、在 TextField 中输入内容或切换开关。
-
5. 捕获待比较的值。 在中读取状态,并将结果保存到
runOnIdle { }变量中。val -
6. 在捕获值与之间将
emulateSavedInstanceStateRestore()。 这是整个测试的关键技巧。第一次 composition 已为state = null赋值;将其置为 null 会迫使第二次访问state时读取第二次 composition 所赋的值,从而证明第二次 composition 确实发生了。如果不将其置为 null,测试断言的仍是原始实例,即使往返过程没有恢复任何内容,测试也会通过。state!! -
7. 调用。 内部流程(引用自
emulateSavedInstanceStateRestore())包含三个StateRestorationTester.android.kt:70-77代码块:先执行runOnIdle,再执行saveStateAndDisposeChildren,最后通过一个空操作代码块等待内容发出。emitChildrenWithRestoredState -
8. 在中重新读取状态,并断言其与捕获值相等。
runOnIdle
Patterns
模式
Pattern: remember
vs rememberSaveable
rememberrememberSaveable模式:remember
与 rememberSaveable
rememberrememberSaveablekotlin
// WRONG
@Test
fun counterIsRestored() {
val tester = StateRestorationTester(rule)
var counter: MutableState<Int>? = null
tester.setContent {
counter = remember { mutableStateOf(0) } // <-- not saveable
Text("${counter!!.value}")
}
rule.runOnIdle { counter!!.value = 7 }
counter = null
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(counter!!.value).isEqualTo(7) } // FAILS: 0
}
// WRONG because: plain remember is dropped on dispose. The KDoc states "state stored via
// regular state() or remember() will be lost" (StateRestorationTester.android.kt:67-68).kotlin
// RIGHT
@Test
fun counterIsRestored() {
val tester = StateRestorationTester(rule)
var counter: MutableState<Int>? = null
tester.setContent {
counter = rememberSaveable { mutableStateOf(0) } // <-- saveable
Text("${counter!!.value}")
}
rule.runOnIdle { counter!!.value = 7 }
counter = null
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(counter!!.value).isEqualTo(7) }
}kotlin
// WRONG
@Test
fun counterIsRestored() {
val tester = StateRestorationTester(rule)
var counter: MutableState<Int>? = null
tester.setContent {
counter = remember { mutableStateOf(0) } // <-- not saveable
Text("${counter!!.value}")
}
rule.runOnIdle { counter!!.value = 7 }
counter = null
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(counter!!.value).isEqualTo(7) } // FAILS: 0
}
// WRONG because: plain remember is dropped on dispose. The KDoc states "state stored via
// regular state() or remember() will be lost" (StateRestorationTester.android.kt:67-68).kotlin
// RIGHT
@Test
fun counterIsRestored() {
val tester = StateRestorationTester(rule)
var counter: MutableState<Int>? = null
tester.setContent {
counter = rememberSaveable { mutableStateOf(0) } // <-- saveable
Text("${counter!!.value}")
}
rule.runOnIdle { counter!!.value = 7 }
counter = null
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(counter!!.value).isEqualTo(7) }
}Pattern: rule.setContent
vs restorationTester.setContent
rule.setContentrestorationTester.setContent模式:rule.setContent
与 restorationTester.setContent
rule.setContentrestorationTester.setContentkotlin
// WRONG
@Test
fun stateIsRestored() {
val tester = StateRestorationTester(rule)
rule.setContent { /* … */ } // <-- bypasses the tester
tester.emulateSavedInstanceStateRestore() // throws
}
// WRONG because: emulateSavedInstanceStateRestore checks `registry != null` and otherwise
// throws IllegalStateException("setContent should be called first!")
// (StateRestorationTester.android.kt:71). The injection only happens via tester.setContent.kotlin
// RIGHT
@Test
fun stateIsRestored() {
val tester = StateRestorationTester(rule)
tester.setContent { /* … */ }
tester.emulateSavedInstanceStateRestore()
}kotlin
// WRONG
@Test
fun stateIsRestored() {
val tester = StateRestorationTester(rule)
rule.setContent { /* … */ } // <-- bypasses the tester
tester.emulateSavedInstanceStateRestore() // throws
}
// WRONG because: emulateSavedInstanceStateRestore checks `registry != null` and otherwise
// throws IllegalStateException("setContent should be called first!")
// (StateRestorationTester.android.kt:71). The injection only happens via tester.setContent.kotlin
// RIGHT
@Test
fun stateIsRestored() {
val tester = StateRestorationTester(rule)
tester.setContent { /* … */ }
tester.emulateSavedInstanceStateRestore()
}Pattern: re-reading the same instance vs nulling between phases
模式:重新读取同一实例与在两个阶段之间置为 null
kotlin
// WRONG
@Test
fun listScrollIsRestored() {
val tester = StateRestorationTester(rule)
lateinit var state: LazyListState
tester.setContent { state = rememberLazyListState(); /* list */ }
rule.onNodeWithTag(LazyListTag).performScrollToIndex(5)
val captured = rule.runOnIdle { state.firstVisibleItemIndex }
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(captured) }
}
// WRONG because: `state` still points at the FIRST composition's instance. The assertion
// passes even if the second composition silently created a fresh state and restored nothing.
// Use a nullable var and null it between phases to force the second access to read from the
// post-restoration composition.kotlin
// RIGHT
@Test
fun listScrollIsRestored() {
val tester = StateRestorationTester(rule)
var state: LazyListState? = null
tester.setContent { state = rememberLazyListState(); /* list */ }
rule.onNodeWithTag(LazyListTag).performScrollToIndex(5)
val captured = rule.runOnIdle { state!!.firstVisibleItemIndex }
state = null // <-- forces re-read
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(state!!.firstVisibleItemIndex).isEqualTo(captured) }
}kotlin
// WRONG
@Test
fun listScrollIsRestored() {
val tester = StateRestorationTester(rule)
lateinit var state: LazyListState
tester.setContent { state = rememberLazyListState(); /* list */ }
rule.onNodeWithTag(LazyListTag).performScrollToIndex(5)
val captured = rule.runOnIdle { state.firstVisibleItemIndex }
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(state.firstVisibleItemIndex).isEqualTo(captured) }
}
// WRONG because: `state` still points at the FIRST composition's instance. The assertion
// passes even if the second composition silently created a fresh state and restored nothing.
// Use a nullable var and null it between phases to force the second access to read from the
// post-restoration composition.kotlin
// RIGHT
@Test
fun listScrollIsRestored() {
val tester = StateRestorationTester(rule)
var state: LazyListState? = null
tester.setContent { state = rememberLazyListState(); /* list */ }
rule.onNodeWithTag(LazyListTag).performScrollToIndex(5)
val captured = rule.runOnIdle { state!!.firstVisibleItemIndex }
state = null // <-- forces re-read
tester.emulateSavedInstanceStateRestore()
rule.runOnIdle { assertThat(state!!.firstVisibleItemIndex).isEqualTo(captured) }
}Pattern: 1 MB Bundle cap
模式:1 MB Bundle 上限
kotlin
// WRONG
@Test
fun megaListSurvives() {
val tester = StateRestorationTester(rule)
tester.setContent {
rememberSaveable { ByteArray(2 * 1024 * 1024) } // 2 MB
}
tester.emulateSavedInstanceStateRestore() // throws IllegalStateException
}
// WRONG because: platformEncodeDecode in StateRestorationTester.android.kt:163 enforces
// `check(bytes.size <= 1024 * 1024) { "Bundle exceeds maximum size (1 MB): ${bytes.size} bytes." }`
// The same cap applies on real devices via Binder transaction limits.kotlin
// RIGHT — keep saved state small. Persist large data via Room/DataStore, save only an id.
@Test
fun megaListSurvives() {
val tester = StateRestorationTester(rule)
tester.setContent {
rememberSaveable { largeRowsId } // a stable key, not the data
}
tester.emulateSavedInstanceStateRestore()
}kotlin
// WRONG
@Test
fun megaListSurvives() {
val tester = StateRestorationTester(rule)
tester.setContent {
rememberSaveable { ByteArray(2 * 1024 * 1024) } // 2 MB
}
tester.emulateSavedInstanceStateRestore() // throws IllegalStateException
}
// WRONG because: platformEncodeDecode in StateRestorationTester.android.kt:163 enforces
// `check(bytes.size <= 1024 * 1024) { "Bundle exceeds maximum size (1 MB): ${bytes.size} bytes." }`
// The same cap applies on real devices via Binder transaction limits.kotlin
// RIGHT — keep saved state small. Persist large data via Room/DataStore, save only an id.
@Test
fun megaListSurvives() {
val tester = StateRestorationTester(rule)
tester.setContent {
rememberSaveable { largeRowsId } // a stable key, not the data
}
tester.emulateSavedInstanceStateRestore()
}Mandatory rules
强制规则
- MUST call (NOT
restorationTester.setContent { }) for the round-trip to work.rule.setContent { } - MUST declare the state reference as a nullable and reassign to
var ... = nullbetween the capture andnull. The assignment forces the secondemulateSavedInstanceStateRestore()access to read the post-restoration composition.!! - MUST use (or another
rememberSaveable { … }integration) for any state expected to survive. PlainSaveableStateRegistryandremembernot behindmutableStateOfARE LOST. Cited atrememberSaveable.StateRestorationTester.android.kt:67-68 - MUST keep the saved Bundle under 1 MB. The check is at .
StateRestorationTester.android.kt:163 - MUST NOT treat as a stand-in for Activity recreation, configuration change, or process death. The KDoc explicitly says "It is not testing the integration with any other life cycles or Activity callbacks." (
emulateSavedInstanceStateRestore()).StateRestorationTester.android.kt:40-41 - MUST NOT combine this skill with — that rule is
createEmptyComposeRule(), notComposeTestRule, so the constructor will not compile.ComposeContentTestRule - PREFERRED: drive the state to a non-default value (scroll, type, toggle) before capturing — a test that asserts on the default value cannot prove restoration occurred.
- PREFERRED: read the captured values via and assert equality, not identity.
rule.runOnIdle { … }
- MUST 调用 ,而不是
restorationTester.setContent { },否则往返测试无法正常工作。rule.setContent { } - MUST 将状态引用声明为 nullable 的 ,并在捕获值与
var ... = null之间重新赋值为emulateSavedInstanceStateRestore()。该赋值会迫使第二次null访问读取恢复后 composition 中的状态。!! - MUST 对所有预期在恢复后保留的状态使用 (或采用其他
rememberSaveable { … }集成方式)。普通SaveableStateRegistry以及未置于remember之下的rememberSaveable都会丢失。引用自mutableStateOf。StateRestorationTester.android.kt:67-68 - MUST 将保存的 Bundle 控制在 1 MB 以下。检查位于 。
StateRestorationTester.android.kt:163 - MUST NOT 将 视为 Activity 重建、配置变更或进程终止的替代方案。KDoc 明确指出:“它不会测试与任何其他生命周期或 Activity 回调的集成。”(
emulateSavedInstanceStateRestore())。StateRestorationTester.android.kt:40-41 - MUST NOT 将此 skill 与 一起使用——该 rule 是
createEmptyComposeRule(),而不是ComposeTestRule,因此构造器无法通过编译。ComposeContentTestRule - PREFERRED: 在捕获值之前将状态驱动至非默认值,例如滚动、输入或切换。只断言默认值无法证明恢复确实发生。
- PREFERRED: 通过 读取捕获值并断言相等,而不是断言对象身份相同。
rule.runOnIdle { … }
Verification
验证
- The test constructs once and calls only
StateRestorationTester(rule).restorationTester.setContent { … } - The hoisted state is , NOT
var state: T? = nullor non-nulllateinit var.var state: T - The test drives the state to a non-default value before capturing.
- Capture happens inside and the result is stored in a
rule.runOnIdle { … }.val - appears between the capture and
state = null.restorationTester.emulateSavedInstanceStateRestore() - All persisted state uses . No plain
rememberSaveable { … }is expected to survive.remember - The total saved size is comfortably under 1 MB. Large blobs are excluded; only ids/keys are saved.
- The test does NOT also assume Activity recreation behaviors (callbacks, ViewModel rebind, etc.).
- 测试仅构造一次 ,并且只调用
StateRestorationTester(rule)。restorationTester.setContent { … } - 提升的状态是 ,而不是
var state: T? = null或非 nullable 的lateinit var。var state: T - 测试在捕获值之前已将状态驱动至非默认值。
- 捕获操作在 中执行,结果保存在
rule.runOnIdle { … }变量中。val - 出现在捕获操作与
state = null之间。restorationTester.emulateSavedInstanceStateRestore() - 所有持久化状态均使用 ,没有预期普通
rememberSaveable { … }能在恢复后保留。remember - 保存数据的总大小明显低于 1 MB,大型数据块已被排除,仅保存 id 或 key。
- 测试没有同时假设 Activity 重建行为,包括回调触发或 ViewModel 重新绑定等。
References
参考资料
- source:
StateRestorationTestercompose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/StateRestorationTester.android.kt:43-77, 128-169 - round-trip canonical test:
LazyListStatecompose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListTest.kt:890-913 - saveable-state-holder regression test:
Switchcompose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SwitchTest.kt:283-310 - Save your UI state guide: https://developer.android.com/topic/libraries/architecture/saving-states
- reference: https://developer.android.com/reference/kotlin/androidx/compose/runtime/saveable/package-summary#rememberSaveable
rememberSaveable - Compose testing overview: https://developer.android.com/develop/ui/compose/testing
- 源码:
StateRestorationTestercompose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/StateRestorationTester.android.kt:43-77, 128-169 - 往返测试的规范测试:
LazyListStatecompose/foundation/foundation/integration-tests/lazy-tests/src/androidTest/kotlin/androidx/compose/foundation/lazy/list/LazyListTest.kt:890-913 - 保存状态持有器的回归测试:
Switchcompose/material3/material3/src/androidDeviceTest/kotlin/androidx/compose/material3/SwitchTest.kt:283-310 - 保存 UI 状态指南:https://developer.android.com/topic/libraries/architecture/saving-states
- 参考文档:https://developer.android.com/reference/kotlin/androidx/compose/runtime/saveable/package-summary#rememberSaveable
rememberSaveable - Compose 测试概览:https://developer.android.com/develop/ui/compose/testing