testing-state-restoration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Testing State Restoration —
StateRestorationTester
Round-Trips Only
rememberSaveable

测试状态恢复——
StateRestorationTester
往返测试仅覆盖
rememberSaveable

StateRestorationTester
is the only first-party way to verify that a Composable's state survives a save/restore cycle. It is narrow — it injects a
LocalSaveableStateRegistry
, snapshots whatever registered through it, throws away the composition, and re-composes with the snapshot restored. It does not restart the Activity, it does not trigger
Application.onCreate
, and it has a hard 1 MB cap on the serialized Bundle. Misunderstanding the scope produces tests that look passing but prove nothing.
StateRestorationTester
是验证 Composable 的状态能否在保存与恢复周期中保留的唯一第一方方式。它的作用范围很窄:它会注入
LocalSaveableStateRegistry
,为通过该注册表注册的内容创建快照,丢弃当前 composition,然后使用恢复后的快照重新 composition。它不会重启 Activity,不会触发
Application.onCreate
,并且对序列化后的 Bundle 有 1 MB 的硬性上限。误解其作用范围会写出看似通过、实则什么都没有证明的测试。

When to use this skill

何时使用此 skill

  • The developer is verifying that
    rememberSaveable
    survives — for a
    LazyListState
    , a TextField value, a screen toggle, etc.
  • The developer asks "how do I test
    rememberSaveable
    in a unit test?"
  • A test calls
    emulateSavedInstanceStateRestore()
    and the state appears unchanged or null.
  • The developer hits
    IllegalStateException: Bundle exceeds maximum size (1 MB)
    .
  • A reviewer asks for a regression test for a save/restore bug fix.
  • 开发者正在验证
    rememberSaveable
    能否保留状态,例如
    LazyListState
    、TextField 值或屏幕开关等。
  • 开发者询问“如何在单元测试中测试
    rememberSaveable
    ?”
  • 测试调用了
    emulateSavedInstanceStateRestore()
    ,但状态看起来没有变化或仍为 null。
  • 开发者遇到
    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).
    StateRestorationTester
    does not exercise that path; use Espresso
    ActivityScenario.recreate()
    plus this skill if both phases need coverage.
  • The state is in a
    ViewModel
    and the developer wants to test
    SavedStateHandle
    . Use the AndroidX ViewModel testing tools.
  • The class skeleton is wrong — fix
    ../structuring-a-compose-test/SKILL.md
    first.
  • 待测试的缺陷涉及 Activity 重建(屏幕旋转会重新创建 Activity,回调会触发,ViewModel 会重新绑定)。
    StateRestorationTester
    不会覆盖该路径;如果两个阶段都需要测试,请使用 Espresso
    ActivityScenario.recreate()
    并结合此 skill。
  • 状态位于
    ViewModel
    中,而开发者希望测试
    SavedStateHandle
    。请使用 AndroidX ViewModel 测试工具。
  • 测试类结构本身不正确——应先修复
    ../structuring-a-compose-test/SKILL.md
    。

Prerequisites

前置条件

  • androidx.compose.ui:ui-test-junit4
    on
    androidTestImplementation
    .
    StateRestorationTester
    is in package
    androidx.compose.ui.test.junit4
    .
  • A
    ComposeContentTestRule
    (i.e. one of
    createComposeRule()
    /
    createAndroidComposeRule<A>()
    ).
    createEmptyComposeRule()
    is NOT compatible because it returns
    ComposeTestRule
    , which has no
    setContent
    .
  • The Composable under test stores its state with
    rememberSaveable { … }
    (or registers via
    SaveableStateRegistry
    ). Plain
    remember
    does NOT survive the round-trip — the KDoc states it explicitly: "the state stored via regular state() or remember() will be lost." (cited at
    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
    注册状态)。普通
    remember
    不会在往返过程中保留状态——KDoc 明确指出:“通过普通 state() 或 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
class StateRestorationTester(private val composeTestRule: ComposeContentTestRule)
, file
StateRestorationTester.android.kt:43
.
  • 2. Use
    restorationTester.setContent { }
    instead of
    rule.setContent { }
    .
    This is non-negotiable: the tester replaces the
    LocalSaveableStateRegistry
    for the wrapped content. Calling
    rule.setContent
    directly bypasses the injection and
    emulateSavedInstanceStateRestore
    will fail with
    "setContent should be called first!"
    (cited at
    StateRestorationTester.android.kt:71
    ).
  • 3. Hoist the state reference as a nullable
    var
    declared above
    setContent
    .
    This is the canonical shape — see
    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 inside
    runOnIdle { }
    and store them in
    val
    s.
  • 6. Set
    state = null
    between the capture and
    emulateSavedInstanceStateRestore()
    .
    This is the load-bearing trick. The first composition assigned a value to
    state
    ; nulling it forces the second
    state!!
    access 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.
  • 7. Call
    emulateSavedInstanceStateRestore()
    .
    The internal flow (cited at
    StateRestorationTester.android.kt:70-77
    ) is three
    runOnIdle
    blocks:
    saveStateAndDisposeChildren
    ,
    emitChildrenWithRestoredState
    , then a no-op block to wait for emission.
  • 8. Re-read the state inside
    runOnIdle
    and assert equality with the captured values.
  • 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. 将状态引用提升为位于
    setContent
    上方的 nullable
    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()
    之间将
    state = null
    。
    这是整个测试的关键技巧。第一次 composition 已为
    state
    赋值;将其置为 null 会迫使第二次访问
    state!!
    时读取第二次 composition 所赋的值,从而证明第二次 composition 确实发生了。如果不将其置为 null,测试断言的仍是原始实例,即使往返过程没有恢复任何内容,测试也会通过。
  • 7. 调用
    emulateSavedInstanceStateRestore()
    。
    内部流程(引用自
    StateRestorationTester.android.kt:70-77
    )包含三个
    runOnIdle
    代码块:先执行
    saveStateAndDisposeChildren
    ,再执行
    emitChildrenWithRestoredState
    ,最后通过一个空操作代码块等待内容发出。
  • 8. 在
    runOnIdle
    中重新读取状态,并断言其与捕获值相等。

Patterns

模式

Pattern:
remember
vs
rememberSaveable

模式:
remember
与
rememberSaveable

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) }
}
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.setContent
与
restorationTester.setContent

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()
}
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
    restorationTester.setContent { }
    (NOT
    rule.setContent { }
    ) for the round-trip to work.
  • MUST declare the state reference as a nullable
    var ... = null
    and reassign to
    null
    between the capture and
    emulateSavedInstanceStateRestore()
    . The assignment forces the second
    !!
    access to read the post-restoration composition.
  • MUST use
    rememberSaveable { … }
    (or another
    SaveableStateRegistry
    integration) for any state expected to survive. Plain
    remember
    and
    mutableStateOf
    not behind
    rememberSaveable
    ARE LOST. Cited at
    StateRestorationTester.android.kt:67-68
    .
  • MUST keep the saved Bundle under 1 MB. The check is at
    StateRestorationTester.android.kt:163
    .
  • MUST NOT treat
    emulateSavedInstanceStateRestore()
    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." (
    StateRestorationTester.android.kt:40-41
    ).
  • MUST NOT combine this skill with
    createEmptyComposeRule()
    — that rule is
    ComposeTestRule
    , not
    ComposeContentTestRule
    , so the constructor will not compile.
  • 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
    rule.runOnIdle { … }
    and assert equality, not identity.
  • 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 将
    emulateSavedInstanceStateRestore()
    视为 Activity 重建、配置变更或进程终止的替代方案。KDoc 明确指出:“它不会测试与任何其他生命周期或 Activity 回调的集成。”(
    StateRestorationTester.android.kt:40-41
    )。
  • MUST NOT 将此 skill 与
    createEmptyComposeRule()
    一起使用——该 rule 是
    ComposeTestRule
    ,而不是
    ComposeContentTestRule
    ,因此构造器无法通过编译。
  • PREFERRED: 在捕获值之前将状态驱动至非默认值,例如滚动、输入或切换。只断言默认值无法证明恢复确实发生。
  • PREFERRED: 通过
    rule.runOnIdle { … }
    读取捕获值并断言相等,而不是断言对象身份相同。

Verification

验证

  • The test constructs
    StateRestorationTester(rule)
    once and calls only
    restorationTester.setContent { … }
    .
  • The hoisted state is
    var state: T? = null
    , NOT
    lateinit var
    or non-null
    var state: T
    .
  • The test drives the state to a non-default value before capturing.
  • Capture happens inside
    rule.runOnIdle { … }
    and the result is stored in a
    val
    .
  • state = null
    appears between the capture and
    restorationTester.emulateSavedInstanceStateRestore()
    .
  • All persisted state uses
    rememberSaveable { … }
    . No plain
    remember
    is expected to survive.
  • 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
    ,而不是
    lateinit var
    或非 nullable 的
    var state: T
    。
  • 测试在捕获值之前已将状态驱动至非默认值。
  • 捕获操作在
    rule.runOnIdle { … }
    中执行,结果保存在
    val
    变量中。
  • state = null
    出现在捕获操作与
    restorationTester.emulateSavedInstanceStateRestore()
    之间。
  • 所有持久化状态均使用
    rememberSaveable { … }
    ,没有预期普通
    remember
    能在恢复后保留。
  • 保存数据的总大小明显低于 1 MB,大型数据块已被排除,仅保存 id 或 key。
  • 测试没有同时假设 Activity 重建行为,包括回调触发或 ViewModel 重新绑定等。

References

参考资料