Testing State Restoration logo

Testing State Restoration

Community
skydoves
testing-state-restoration

Use this skill to test `rememberSaveable` round-trips with `StateRestorationTester`, the only supported tool for proving Compose state survives process death and configuration change. Covers the constructor (`StateRestorationTester(rule: ComposeContentTestRule)`), why `restorationTester.setContent { }` MUST replace `rule.setContent { }`, the `state = null` between phases trick that proves restoration actually happened, the 1 MB Bundle cap, and what is NOT exercised (Activity lifecycle, configuration changes, plain `remember`). Use when the developer asks "how do I test rememberSaveable", "test state survives rotation", "state is lost after restore", "Bundle exceeds maximum size", or shows a test that re-reads the same state reference after `emulateSavedInstanceStateRestore` and is confused why nothing changed.

Overview

Publisherskydoves
Repositoryandroid-testing-skills
Skill nametesting-state-restoration
Stars
338
Forks
14
Bundled files
Instructions only
LicenseApache-2.0
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by skydoves on GitHub. Read the source before you install it.

Installation

Install the Testing State Restoration AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/skydoves/android-testing-skills/tree/main/compose/patterns/testing-state-restoration
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/skydoves/android-testing-skills.git /tmp/android-testing-skills
mkdir -p .claude/skills
cp -r /tmp/android-testing-skills/compose/patterns/testing-state-restoration .claude/skills/testing-state-restoration
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Testing State Restoration in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Testing State Restoration on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Testing State Restoration is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Testing State Restoration — StateRestorationTester Round-Trips Only 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.

When to use this 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.

When NOT to use this 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.

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).

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 vals.

  • 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.

Patterns

Pattern: remember vs 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) }
}

Pattern: rule.setContent vs 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()
}

Pattern: re-reading the same instance vs nulling between phases

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

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.

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.).

References

Frequently asked questions

What does the Testing State Restoration AI skill do?

Use this skill to test `rememberSaveable` round-trips with `StateRestorationTester`, the only supported tool for proving Compose state survives process death and configuration change. Covers the constructor (`StateRestorationTester(rule: ComposeContentTestRule)`), why `restorationTester.setContent { }` MUST replace `rule.setContent { }`, the `state = null` between phases trick that proves restoration actually happened, the 1 MB Bundle cap, and what is NOT exercised (Activity lifecycle, configuration changes, plain `remember`). Use when the developer asks "how do I test rememberSaveable", "t...

Why use Testing State Restoration on TypingMind?

Because you install it once and use it with any model. Testing State Restoration is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Testing State Restoration in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/skydoves/android-testing-skills/tree/main/compose/patterns/testing-state-restoration. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Testing State Restoration?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Testing State Restoration?

As many as you like. As long as a model supports skills, you can use Testing State Restoration with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Testing State Restoration AI skill free?

Yes. It is published on GitHub by skydoves under the Apache-2.0 license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇