AI-generated Flutter tests are unit, widget, golden or integration tests written by a coding agent such as Anthropic Claude Code, OpenAI Codex, GitHub Copilot or Google Antigravity. They are only reliable when you choose the test layer, spell out what must be true, let the agent run the tests itself, and review every assertion. Coding agents are very good at producing Flutter tests and surprisingly good at producing tests that prove nothing: a test that pumps a widget and checks that a Scaffold exists will pass forever and catch no bugs. Over 4+ years and 20+ shipped Flutter apps, I have settled on a tool-agnostic workflow that gets agents to write tests that fail when the app is broken.
Can AI write reliable Flutter tests?
Yes, if you give the agent the right layer, a precise contract and a way to run the tests itself. Without those, agents tend to write tests that compile and pass but assert very little. Reliability comes from your instructions and your review, not from the model choosing well on its own.
In my practice the agent does the typing and I do the deciding. I choose what to test and at which layer, I write the expected behaviour into the prompt, and I read every assertion before the test is merged.
Key definitions
- Widget contract: what the user sees before an action, which widget they interact with, and what must be true afterwards. It is the spec you hand the agent instead of the implementation.
- Golden file: a reference PNG that
matchesGoldenFilecompares a rendered widget against. - pumpAndSettle timeout: the limit, 10 minutes by default, after which
pumpAndSettle()throws because frames are still being scheduled. - Patrol: a multiplatform end-to-end UI testing framework for Flutter from LeanCode that can interact with native UI such as permission dialogs and notifications.
Should the agent write a unit, widget or integration test?
Pick the layer before you prompt. Unit tests check a single function, method or class, widget tests check a single widget, and integration tests check a complete app or a large part of it, usually on a device or emulator. Each step up buys confidence at the cost of maintenance and speed.
The official Flutter testing overview summarises the trade-offs like this:
| Trade-off | Unit | Widget | Integration |
|---|---|---|---|
| Confidence | Low | Higher | Highest |
| Maintenance cost | Low | Higher | Highest |
| Dependencies | Few | More | Most |
| Execution speed | Quick | Quick | Slow |
Flutter's guidance is that a well-tested app has many unit and widget tests, tracked by code coverage, plus enough integration tests to cover all the important use cases. There is no fixed ratio. My rule for agents: view models and repositories get unit tests, every screen state (loading, empty, error, loaded) gets a widget test, and only the flows that make money or lose data get integration tests. That split is much easier when logic already lives outside widgets, which is one reason I push MVVM in Flutter on every project.
How do I prompt an agent to write a widget test that catches bugs?
Describe the widget contract, not the implementation. Tell the agent what the user sees before an action, which widget to interact with and by which Key, how to advance frames, and what must be true afterwards. Vague prompts like "add tests for the login screen" produce tests that only check that the screen renders.
A prompt I would actually send looks like this:
Write a widget test in test/login_screen_test.dart for LoginScreen.
Contract:
- Initially the submit button (Key('submit_btn')) is visible and no error text is shown.
- Tapping submit with an empty email shows the text 'Email is required'.
- Use testWidgets, wrap the screen in MaterialApp, find widgets with find.byKey or find.text.
- After tap(), call pump(). Only use pumpAndSettle() where an animation must finish.
- Every test must end with at least one expect() on visible output.
Run flutter test test/login_screen_test.dart and iterate until it passes
without changing LoginScreen.
That produces something close to this (LoginScreen is a hypothetical screen):
testWidgets('shows an error when email is empty', (tester) async {
await tester.pumpWidget(const MaterialApp(home: LoginScreen()));
expect(find.text('Email is required'), findsNothing);
await tester.tap(find.byKey(const Key('submit_btn')));
await tester.pump();
expect(find.text('Email is required'), findsOneWidget);
});
Three documented details make this work. testWidgets() creates a new WidgetTester for each test case and is used in place of test() (widget testing introduction). In the test environment Flutter does not rebuild automatically when state changes, so every tap(), enterText() or drag() must be followed by pump() or pumpAndSettle() (tap, drag and enter text). And when several widgets share the same text, such as list items, the Flutter cookbook on finders recommends giving each one a Key and finding it with find.byKey. Asking the agent to add Keys to the widgets it tests is one of the cheapest ways to make tests stable.
Use the right matcher too: findsOneWidget, findsNothing, findsWidgets for one or more, and findsNWidgets for an exact count. An agent that writes findsWidgets where exactly one result is correct has written a weaker test.
What is the difference between pump and pumpAndSettle, and why does pumpAndSettle time out?
pump() schedules one frame and rebuilds. Given a duration, it advances the clock but still does not schedule multiple frames. pumpAndSettle() keeps pumping until no frames are scheduled, which effectively waits for animations to finish. It times out when something never stops animating.
The pumpAndSettle API defaults to a 100 ms step and a 10 minute timeout, and it throws if frames are still being scheduled when the timeout is reached. The classic cause is an indeterminate, spinning progress indicator. Agents reach for pumpAndSettle() everywhere because it "just works" until a loading spinner appears. My instruction is simple: use pump() after taps, use pumpAndSettle() only for animations that end, and never wrap a loading state in it. The official integration-test skill gives the same advice: on a PumpAndSettleTimedOutException, check for infinite animations. When an agent cannot explain a timeout, my Flutter bug-fixing guide covers the debugging side.
How do I make a coding agent run flutter test by itself?
Give the agent the exact commands in its instruction file and let it run them, either as shell commands or through the official Dart and Flutter MCP server (dart_mcp_server, run with dart mcp-server). An agent that can run tests can see its own failures and fix them. An agent that cannot will hand you code that has never executed.
The commands come straight from the Flutter docs. flutter test runs the package's tests and should be used instead of dart test (Flutter CLI reference). Agents iterate faster on narrow runs:
flutter test test/counter_test.dart
flutter test --plain-name "Test start, increment, decrement"
Test files must end in _test.dart and live under test/, because that is how the runner finds them (unit testing introduction). Put these commands where your agent reads them:
- Claude Code:
./CLAUDE.mdor./.claude/CLAUDE.md. Claude Code readsAGENTS.mdonly when noCLAUDE.mdexists in the working directory or above (v2.1.277 and later); otherwise import it fromCLAUDE.md(Claude Code memory docs). My Claude Code guide for Flutter developers covers the rest of that file. - Codex:
AGENTS.md, read from the git root down to the current directory, with closer files overriding earlier ones (Codex AGENTS.md docs). - GitHub Copilot:
.github/copilot-instructions.md, path-specific.github/instructions/NAME.instructions.mdfiles, orAGENTS.mdfiles where the nearest one wins (GitHub Copilot docs). I walk through the full setup in GitHub Copilot agent mode for Flutter.
I covered how I structure that file for Flutter in my comparison of Antigravity, Claude Code and Cursor. For testing I add a short section:
## Testing
- Unit tests for view models and repositories; widget tests for every screen state.
- Find widgets by Key. Add a Key rather than finding by index.
- pump() after interactions; pumpAndSettle() only for animations that end.
- Never edit production code just to make a test pass without telling me.
- Never run flutter test --update-goldens. Report golden failures instead.
- Done means: flutter analyze is clean and flutter test passes.
What is the run_tests tool in the Dart and Flutter MCP server?
run_tests is a tool in the official Dart and Flutter MCP server that runs Dart or Flutter tests "with an agent centric UX". It is disabled by default, according to the dart_mcp_server README. Its description tells agents to always use it instead of dart test or flutter test shell commands once it is enabled.
The server starts with dart mcp-server, needs Dart 3.9.0-163.0.dev or later, and is marked experimental, so expect changes (Dart and Flutter MCP server docs). It gives the assistant analyzer diagnostics, symbol resolution, test runners and runtime inspection. For Copilot in VS Code, the documented config is .vscode/mcp.json:
{
"servers": {
"dart": { "command": "dart", "args": ["mcp-server"] }
}
}
Antigravity reads the same server from .agents/mcp_config.json in the project or ~/.gemini/config/mcp_config.json globally, under mcpServers.dart. To turn on run_tests, the README says to use the --enable flag with a tool name or category (run_tests is in the cli category). Enabling a category enables its default-off tools, and --disable wins over --enable. For every other editor, see my Dart and Flutter MCP server setup guide.
How do I install the official Flutter agent skills for testing?
Install the skills from the flutter/agent-plugins and dart-lang/skills repositories. Skills are on-demand procedural guides that teach an assistant tasks such as writing widget tests (Flutter agent skills docs). Two of the ten Flutter skills cover testing: flutter-add-widget-test and flutter-add-integration-test, both maintained in the official Flutter repository.
The universal install, which the Flutter docs list for agents such as Copilot and Antigravity's CLI:
npx skills add flutter/agent-plugins --skill '*' --agent universal --yes
npx skills add dart-lang/skills --skill '*' --agent universal --yes
Claude Code and Codex install a plugin instead:
claude plugin marketplace add flutter/agent-plugins
claude plugin install dart-flutter@dart-flutter
codex plugin marketplace add flutter/agent-plugins
codex plugin add dart-flutter@dart-flutter
For Claude Code, the docs note that rules must be added to CLAUDE.md manually. In Antigravity the integration is under Settings, Customizations, Dart and Flutter integration. The widget-test skill follows the same loop as my prompt above: pumpWidget, find, assert the initial state, simulate a gesture, pump, assert the new state, then run flutter test on that file until it passes. The integration skill adds ValueKeys to critical widgets, explores the running app through MCP tools, then converts that flow into a file under integration_test/.
How do golden tests work in Flutter?
A golden test renders a widget to an image and compares it with a stored reference PNG. You call matchesGoldenFile inside expectLater and await it, because the matcher is asynchronous. A failure means the pixels changed, and someone has to decide whether that change was intended.
testWidgets('price card matches golden', (tester) async {
await tester.pumpWidget(const MaterialApp(home: PriceCard()));
await expectLater(
find.byType(PriceCard),
matchesGoldenFile('goldens/price_card.png'),
);
});
The Finder must match exactly one widget, and the image comes from its nearest RepaintBoundary ancestor. Reference files are created or updated with flutter test --update-goldens. Tests use the Ahem font, which draws squares, unless you load real fonts with FontLoader or in flutter_test_config.dart, and custom fonts can render differently across platforms and Flutter versions.
Is it safe to let an AI agent run flutter test --update-goldens?
No. Running --update-goldens rewrites the reference images so the failing test passes, which is exactly what an agent under pressure to "make the tests green" will try. It hides the regression instead of fixing it. Updating goldens is a human decision made after looking at the diff.
The Flutter DevTools team's testing policy lists three causes of a golden failure: an intentional UI change, a Flutter framework change, or an unintentional UI change. Unintentional changes must not be accepted. The same document makes three practical points about CI:
- Goldens generated locally may still fail on CI because of macOS environment differences.
- The recommended fix is to take the regenerated goldens from the failed CI run and review them.
- A local update requires the same Flutter version as CI.
That also answers the common question of why goldens pass locally and fail on CI.
A rule in CLAUDE.md is context, not enforcement. To block the command in Claude Code, use a PreToolUse hook on the Bash matcher. Exit code 2 blocks the command and sends stderr back to Claude (Claude Code hooks guide). Save this as .claude/hooks/block-update-goldens.sh and make it executable (it needs jq):
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command')
if echo "$COMMAND" | grep -q -- "--update-goldens"; then
echo "Blocked: golden updates need human review. Report the failing golden instead." >&2
exit 2
fi
exit 0
flutter test has no short alias for --update-goldens in the flutter_tools source, so matching the long flag covers it. It will also block any shell command that merely contains that string, such as an echo.
Then register it in .claude/settings.json, which you can commit for the whole team:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-update-goldens.sh"
}
]
}
]
}
}
Treat this hook as a guardrail against accidental use, not a security boundary. It only sees shell commands run through the Bash tool. MCP tools are matched under their own mcp__<server>__<tool> names, so a test run through the MCP run_tests tool goes around it, and nothing stops an agent from editing the PNG files directly. That is why checklist item 5 below still matters.
When is integration_test not enough, and when should I use Patrol?
Use integration_test for flows that stay inside Flutter's UI. According to the Flutter integration testing docs, it cannot interact with native platform UI such as permission dialogs, notifications or platform views. For apps that need those native interactions, the docs point to Patrol by LeanCode (the patrol package).
Setting up integration_test is short:
flutter pub add "dev:integration_test:{sdk: flutter}"
flutter test integration_test/app_test.dart
Call IntegrationTestWidgetsFlutterBinding.ensureInitialized() at the start of main() in each file. For Firebase Test Lab, note that a standard --release build does not include package:integration_test, so the docs build with flutter build apk --debug.
Patrol, from verified publisher leancode.co, is a multiplatform end-to-end UI testing framework for Flutter. It can interact with permission dialogs, notifications and WebViews, change device settings and toggle Wi-Fi. It adds full test isolation and sharding, and works with device farms such as Firebase Test Lab, BrowserStack, LambdaTest, SauceLabs and AWS Device Farm. It runs through its own CLI and requires Android SDK 21 or later (Patrol getting started):
flutter pub global activate patrol_cli
patrol test -t patrol_test/example_test.dart
My practice: an agent writes the integration_test flow first, and I move a test to Patrol only when it must cross a native boundary, such as a location permission prompt in a travel app like TourVista.
How do I mock HTTP calls in Flutter unit tests with mockito?
Inject the HTTP client into the class under test, generate a mock with mockito, and stub each success and failure response. The Flutter mocking cookbook gives three reasons to mock: live services make tests slow, cause flaky failures, and make it hard to cover every success and failure case.
flutter pub add http dev:mockito dev:build_runner
dart run build_runner build
Annotate the test with @GenerateMocks([], customMocks: [MockSpec<http.Client>(as: #MockHttpClient)]), then stub calls with when(...).thenAnswer(...). Adapted from the cookbook, where fetchAlbum takes an http.Client and throws on any non-200 response:
final url = Uri.parse('https://jsonplaceholder.typicode.com/albums/1');
test('returns an Album on 200', () async {
final client = MockHttpClient();
when(client.get(url)).thenAnswer((_) async =>
http.Response('{"userId": 1, "id": 2, "title": "mock"}', 200));
expect(await fetchAlbum(client), isA<Album>());
});
test('throws on 404', () {
final client = MockHttpClient();
when(client.get(url)).thenAnswer((_) async => http.Response('Not Found', 404));
expect(fetchAlbum(client), throwsException);
});
Mock the boundary (HTTP, storage, platform plugins), never the view model or repository you are actually testing. How easy this is depends on your state layer, which I compare in Riverpod vs BLoC.
How do I review AI-generated Flutter tests?
Review agent tests as harder than agent code, because a bad test gives false confidence. I check every new or changed test against a short list before merging, and I reject the change if any item fails, even when the suite is green.
- Does it assert anything meaningful? Each test should end with an
expecton visible output or returned values, not just "it rendered". - Would it fail if the feature broke? I sometimes break the code on purpose and rerun. If the test stays green, it is decoration.
- Are mocks replacing the thing under test? A test where the repository is mocked and the assertion checks the mock's return value tests mockito, not your app.
- Were assertions edited to pass? In the diff, watch for changed expected values, loosened matchers (
findsOneWidgettofindsWidgets), newskipflags, or deleted tests. - Did golden files change? Any modified PNG under your goldens folder needs a human look.
- Is timing honest?
pumpAndSettle()around a spinner, or arbitrary long pumps, usually hide a real problem. - Did production code change? If the agent touched
lib/to make a test pass, that is a bug fix and needs its own review.
Frequently Asked Questions
What is a golden test in Flutter?
A golden test renders a widget to an image and compares it with a stored reference PNG, the golden file. You write it with expectLater(finder, matchesGoldenFile('name.png')), and you create or update the reference images with flutter test --update-goldens, which should be a human decision after reviewing the diff.
Where do Flutter test files go and how are they named?
Unit and widget test files live under the test/ folder and must end in _test.dart, because that is the convention the test runner uses to find them. Integration tests go in a separate integration_test/ folder and run with flutter test integration_test/app_test.dart.
How do I measure the coverage of tests an AI agent wrote?
Run flutter test --coverage. It writes coverage data to coverage/lcov.info by default, and --branch-coverage adds branch coverage. Coverage shows which lines ran, not whether the assertions are meaningful, so it does not replace reviewing each agent-written test.
Does a Flutter release build include integration_test?
No. The Flutter integration testing docs note that a standard --release build does not include package:integration_test, so for Firebase Test Lab they build the app with flutter build apk --debug.
Why do Flutter golden tests pass locally but fail on CI?
Rendering differs between environments. Fonts can render differently across platforms and Flutter versions, and the DevTools team notes that locally generated goldens can fail on CI because of macOS environment differences. Their advice is to take regenerated goldens from the failed CI run, review them, and match CI's Flutter version for local updates.
Can integration_test tap a native permission dialog or notification?
No. The Flutter docs state that integration_test cannot interact with native platform UI such as permission dialogs, notifications or platform views, and point to the patrol package for apps that need those interactions. Patrol can handle permission dialogs, notifications and WebViews, and runs through patrol_cli.
How do I install the official Flutter agent skills for testing?
Run npx skills add flutter/agent-plugins --skill '*' --agent universal --yes, plus the same command for dart-lang/skills. In Claude Code, install the dart-flutter plugin from the flutter/agent-plugins marketplace instead. The testing skills are flutter-add-widget-test and flutter-add-integration-test.
If you want an agent workflow like this set up on your Flutter codebase, with instruction files, MCP tooling and a test suite that actually gates merges, see my Flutter AI development service or get in touch.