/flutter:testing-strategyfrom Flutter Skills
Enforces a test doctrine that shapes suites to code rather than a fixed pyramid ratio. Pure logic goes to Flutter-free packages tested with package:test; uses seeded fuzz, round-trip goldens, bare-implements fakes, real Drift engine, headless ProviderContainer overrides, and file-level coverage floors.
Ships in Flutter Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Tests are the only correctness instrument you control at build time: shape the suite
to the code, not to a decades-old ratio, and make each test assert behaviour a build
either passes or fails. Applies to every test under test/ and integration_test/.
Read the reference for the task at hand:
references/test-layers.md — per-layer harness, imports, teardown, edge tables (pure core, in-memory Drift, headless Notifier, integration).references/property-and-fakes.md — fakes-over-mocks, enum-driven fake state, seeded fuzz, independent oracles, absence-of-a-failure-class tests.references/coverage-and-budget.md — file-level floors, the coverage-lies-upward fix, the suite-time budget, and the manual-pass handoff.Run scripts/check_test_hygiene.sh and scripts/run_tests.sh before a PR.
Golden, RTL, and a11y widget mechanics live in widget-golden-and-a11y-testing; this
skill governs everything below the pixel.
f(input) -> output
is a unit or property test, never a pumpWidget. Driving pure logic through the
widget tree is slower, flakier, and hides which layer broke.Clock. Domain math
lives in pure Dart with zero Flutter/plugin/IO imports, tested with package:test
(not flutter_test). The one time type is package:clock's Clock — NEVER
DateTime.now(), never a bespoke ClockService. Pure core reads the ambient
clock.now(), pinned in tests with withClock(Clock.fixed(t), …); Riverpod/feature
code reads the injected clockProvider, overridden with
clockProvider.overrideWithValue(Clock.fixed(t)) (seam owned by
value-objects-money-and-units). The ban is structural: a pure package declares no
Flutter SDK constraint.decode(encode(x)) == x) and rounding goldens at half-way/boundary
values; every universal claim is a seeded fuzz loop (for (var seed = 0; seed < N; seed++)) or property test, checked against an independent oracle — never
the production function under test. Print the generated input in reason: so a
failure is its own minimal repro. == on integers only; closeTo(x, 1e-9) on
doubles.NativeDatabase.memory(), never a mocked DAO — a mocked DAO proves nothing about
SQL, constraints, indexes, or migrations. Mock repositories only above the data
layer. addTearDown(db.close) and close streams synchronously so reactive
.watch() streams do not leak "Timer still pending".implements fakes over mocks for code you own. A class FakeX implements X (no noSuchMethod superclass) makes an interface change a compile
error, models the risk (state, not call-order) as a field, and doubles as the
contract's documentation. Reserve mocktail for genuinely external dependencies;
never mockito/@GenerateMocks (codegen, no null-safety win).registerFallbackValue for every custom type passed to any()/captureAny()
in setUpAll. mocktail throws at runtime, not compile time, on a missing
fallback — this is the single most common mocktail failure.ProviderContainer. Override provider
dependencies via overrideWith; never pump a widget to test state. Assert on the
exposed AsyncValue/state, drive actions through .notifier, and dispose the
container in teardown.assert(sum(result) == total)) —
free in release, catches the bug the moment it happens.ci-pipeline-and-gates owns that). Instead hold a 100% floor on the handful of
files (migrations, the money/allocate primitive, the parser with wire-format
traps) where a gap is silent data loss — enforced by reading the diff, not by
counting lines. A directory or global percentage gate rewards vanity tests and
exclusion churn. First fix the coverage-lies-upward gap: flutter test --coverage omits files no test imports, so the number overstates safety.pumpAndSettle() on an indefinite animation (splash, shimmer, spinner)
— it hangs on a 10-minute timeout. Use timed pump(Duration) with fakeAsync.package:test vs flutter_test)Pure logic runs under dart test with no widget binding; only UI and plugin-wrapper
tests need flutter_test.
// test/domain/money_test.dart — pure Dart, `dart test`, no flutter_test import.
import 'package:test/test.dart';
import 'package:app_core/app_core.dart';
void main() {
// Round-trip: encoding is lossless across the ISO-4217 exponent range.
test('minor-units round-trip for exponents 0, 2, 3', () {
for (final currency in [Currency.jpy, Currency.usd, Currency.kwd]) {
final money = Money(amountMinor: 12345, currency: currency);
expect(Money.parse(money.format(), currency), equals(money));
}
});
}
Production reads clock.now(); tests freeze it so time-dependent logic is
deterministic — no wall clock, no flake.
// Production: a Reminder is due when its target time has passed.
bool isDue(Reminder r) => !clock.now().isBefore(r.dueAt);
// test/domain/reminder_test.dart
test('reminder is due exactly at its due instant', () {
final due = DateTime.utc(2026, 1, 1, 9);
withClock(Clock.fixed(due), () {
expect(isDue(Reminder(dueAt: due)), isTrue);
});
});
For code behind a provider, inject clockProvider and freeze it in a container test
with clockProvider.overrideWithValue(Clock.fixed(due)) — same Clock, same fixed
instant, driven through Riverpod instead of the ambient zone.
Twenty lines of package:test give you what a stale property package would, with the
generated input as the built-in minimal repro. The oracle must be independent of the
function under test.
// test/domain/allocate_test.dart
test('allocate: parts always sum to the input (fuzz)', () {
final rng = Random(0xC0FFEE);
for (var seed = 0; seed < 500; seed++) {
final n = rng.nextInt(20) + 1;
final total = rng.nextInt(100000);
final weights = List.generate(n, (_) => rng.nextInt(500));
final parts = allocate(amountMinor: total, weights: weights);
expect(parts.fold(0, (a, b) => a + b), equals(total),
reason: 'seed=$seed total=$total weights=$weights'); // its own repro
}
});
// test/data/order_dao_test.dart
void main() {
late AppDatabase db;
setUp(() => db = AppDatabase(NativeDatabase.memory()));
tearDown(() => db.close()); // reactive .watch() streams must not leak timers
test('CHECK constraint rejects a negative quantity', () {
expect(
() => db.orderDao.insertItem(const OrderItem(quantity: -1)),
throwsA(isA<SqliteException>()), // proves the real constraint, not a stub
);
});
}
ProviderContainer// test/features/cart/cart_notifier_test.dart
void main() {
test('addItem publishes the new total', () async {
final container = ProviderContainer(
overrides: [orderRepositoryProvider.overrideWith((ref) => _FakeOrderRepo())],
);
addTearDown(container.dispose);
await container.read(cartNotifierProvider.future);
await container.read(cartNotifierProvider.notifier).addItem(_anItem);
final state = container.read(cartNotifierProvider);
expect(state, isA<AsyncData<CartState>>());
expect(state.requireValue.totalMinor, 1299);
});
}
ProviderContainer.test() (Riverpod 3.x) auto-disposes and is the preferred form when
available; otherwise addTearDown(container.dispose).
fakeAsynctest('debounced search fires once after the window', () {
fakeAsync((async) {
final calls = <String>[];
final debouncer = Debouncer(const Duration(milliseconds: 300));
debouncer.run(() => calls.add('a'));
async.elapse(const Duration(milliseconds: 299));
expect(calls, isEmpty);
async.elapse(const Duration(milliseconds: 1));
expect(calls, ['a']);
});
});
f(input) -> output logic through
pumpWidget. Slower, flakier, hides the broken layer.DateTime.now() / ambient Random() reachable from domain logic. Makes
"identical inputs -> identical output" untestable; inject Clock and a seed.flutter_test imported into a pure package. Breaks the structural boundary and
slows the fastest tier; the package should declare no Flutter SDK constraint.NativeDatabase.memory().== on doubles, or covering a universal claim with one lucky example instead of
a fuzz loop over an independent oracle.registerFallbackValue for a custom any() argument — a runtime throw
no compiler catches.pumpAndSettle() on an indefinite indicator — hangs on the 10-minute timeout.expect, shared mutable state across tests, or a vague
name like test('works').package:test, widget/integration only where the UI/plugin seam is the point.clock.now(), never DateTime.now(); tests pin it with
withClock.reason:.NativeDatabase.memory(), not a mocked DAO;
db.close() in teardown.implements fakes; mocktail is reserved for
external deps with registerFallbackValue for every custom any() type.ProviderContainer overrides, disposed in
teardown; no widget pumped to test state.assert tripwire.pumpAndSettle() on an indefinite animation; timers driven by fakeAsync.widget-golden-and-a11y-testing for golden lanes, the overflow/RTL matrix, and honest a11y limits.value-objects-money-and-units for the allocate() primitive and Clock injection this skill tests.persistence-drift for the DAO/value-object seam the in-memory tests exercise.run-migration for the forward-only migration ritual whose from→to paths get the 100% floor.error-handling-typed-results for the sealed Result/Failure the exhaustive-switch tests assert on.async-safety for the dropped-Future holes the silence-review checklist targets.service-boundary-and-native for the injectable ports the fakes stand in for.ci-pipeline-and-gates for how these lanes and greps are wired as gates.seeded-determinism-and-golden-vectors for pinning a seeded generator with a frozen fingerprint table when output must reproduce across devices and releases.package:clock — https://pub.dev/packages/clockpackage:fake_async — https://pub.dev/packages/fake_asyncpackage:mocktail — https://pub.dev/packages/mocktailexamples/allocate_property_test.dart (opens in a new tab)examples/in_memory_drift_test.dart (opens in a new tab)examples/notifier_container_test.dart (opens in a new tab)references/coverage-and-budget.md (opens in a new tab)references/property-and-fakes.md (opens in a new tab)references/test-layers.md (opens in a new tab)scripts/check_test_hygiene.sh (opens in a new tab)scripts/run_tests.sh (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub zakariaf/flutter-skills --plugin flutter40 skills in this plugin
/accessibility-as-codeEnforces accessibility as a correctness property authored into each widget — Semantics(button/label) or ExcludeSemantics on every node, a11y state read from MediaQuery not app state, never MediaQuery.withClampedTextScaling / textScaleFactor / FittedBox / TextOverflow.ellipsis to fit a label, non-color redundant channels (icon+label+shape+text) for every state, contrast against composited backgrounds (4.5:1 body / 3:1 large), 44px single-tap targets, OrdinalSortKey traversal, and honoring boldText / reduce-motion. Use when adding a GestureDetector/InkWell or any tap target, adding an Icon or Image, reaching for withClampedTextScaling/FittedBox/ellipsis/textScaleFactor to make text fit, encoding state via color, sizing type, ordering focus traversal, or reviewing any View for screen-reader/switch/low-vision support./adaptive-layoutEnforces adapting layout by available CONSTRAINTS/size, never device or platform checks — LayoutBuilder + MediaQuery.sizeOf/paddingOf/viewInsetsOf (not .of) for narrow rebuilds, Material 3 window size classes (compact <600, medium 600-840, expanded 840-1200, large >1200) as the breakpoint vocabulary, navigation affordance chosen by width (NavigationBar → NavigationRail → NavigationDrawer), list-detail single-pane-vs-two-pane, readable max-width via ConstrainedBox, Flexible/Expanded/FractionallySizedBox over fixed widths, SafeArea + display cutouts + keyboard insets, never lock orientation, foldable/hinge awareness via MediaQuery.displayFeatures, and golden-matrix verification across sizes. Use when building responsive or adaptive UI, tablet/desktop/foldable support, master-detail or two-pane screens, a NavigationRail-vs-BottomNav shell, breakpoints, LayoutBuilder, MediaQuery sizing, SafeArea/cutouts, or fixing overflow at large widths./ads-and-iap-monetizationEnforces opt-in, rewarded-first monetization over the service seam — a rewarded view grants exactly one benefit and only on a genuine reward outcome (a sealed Rewarded/Dismissed/NoFill), earn loops capped per day against an injected Clock, the earn control preloaded and hidden unless an ad is loaded so a fresh account never dead-ends on "no ads available" (a Guideline 2.1 risk), interstitials only at a natural break under a count-and-elapsed cap owned by the service so callers stay dumb, no banner on the primary work surface, one non-consumable unlock plus Restore re-checked each launch and committed through the single write path before the UI reacts, one derived isEntitled provider as the only gate, and the entitlement restored BEFORE the ad SDK initializes so a paying user never starts it, resolves consent, or sees a tracking prompt. Use when adding ads, wiring a rewarded earn loop, placing an interstitial, building a paywall, gating an entitlement, or setting up ad units./app-startup-and-bootstrapEnforces a fixed main() cold-launch order — crash-log sink + FlutterError.onError + PlatformDispatcher.onError installed BEFORE any code that can throw, settings/theme read before runApp so the first frame paints correct, real infra constructed in a composition-root bootstrap() and injected via ProviderScope overrideWithValue over throwing placeholder providers, non-blocking warm-up deferred to addPostFrameCallback, exactly two error handlers with NO runZonedGuarded, ProviderException unwrapped before logging, and a WidgetsBindingObserver that flushes durable state on background/resume. Use when editing lib/main.dart, main_<flavor>.dart, bootstrap.dart or app.dart, reordering anything in main(), adding a splash/onboarding/permission gate, restoring theme before first paint, wiring a DB or service into ProviderScope, handling app-lifecycle background/resume flushes, or chasing cold-start latency, ANRs, or first-frame jank./async-safetyEnforces no-silent-failure async discipline in Flutter/Dart — the arrow-callback Future-drop hole no lint catches (`onTap: () => vm.save(x)`), void-returning event handlers, a mounted/ref.mounted guard after EVERY await before touching BuildContext, capturing Navigator/ScaffoldMessenger before the gap, honest `unawaited()` that always ends in catchError, no empty/bare catches, `rethrow` over `throw e`, and disposing every StreamSubscription/StreamController/Timer/sink. Use when writing or reviewing async/await, wiring onTap/onPressed/onSubmitted or any VoidCallback, touching BuildContext after an await, writing initState/dispose/addPostFrameCallback, adding a Timer or Future.delayed, writing a try/catch, or seeing use_build_context_synchronously, cancel_subscriptions, close_sinks, unawaited_futures, or discarded_futures./ci-pipeline-and-gatesEnforces a lean GitHub Actions Flutter CI where every gate maps to one named release-blocking contract — pinned runner + subosito/flutter-action@v2 toolchain, dart format --set-exit-if-changed, flutter analyze --fatal-infos, build_runner and drift schema freshness (git diff --exit-code), flutter test --test-randomize-ordering-seed random, static import/banned-string greps that catch what runtime can't, coverage-as-report-never-a-gate with the upward-lie fixed, verify-never-bless goldens (no --update-goldens in CI), and an honest statement of what CI cannot prove (audio, real fonts, on-device behaviour). Use when editing .github/workflows/*.yml, adding or removing a job or step, wiring a codegen/schema/format/analyze/coverage gate, writing a grep-based policy test or gate script under test/policy or tool/, pinning action versions, or claiming CI proves something it can't.Other plugins' skills for the same job