iamantoniodinuzzo/claude-flutter/unit-test

Claude Code and agent skill by iamantoniodinuzzo/claude-flutter

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Generate, update, or repair unit tests for a Flutter feature path or single Dart class. Knows what to test (domain models, services, notifiers, providers, exceptions) and what to skip (widgets, generated code, Firebase repos). Stresses code with adversarial edge cases instead of merely satisfying it — expected values come from the contract, never from running the code; red tests that expose real bugs are reported, never weakened. Uses mocktail, GWT pattern, Riverpod 3.x ProviderContainer, and a…

Install

npx vskill@latest install iamantoniodinuzzo/claude-flutter/unit-test

SKILL.md

The same SKILL.md was published earlier as iamantoniodinuzzo/claude-flutter/unit-test.

unit-test

Runtime and resources

Use the current agent's native file, search, shell, and question tools; plain-text questions and direct sequential scans are valid fallbacks. Subagents are optional and require host permission. Bundled paths below are relative to this installed skill directory; application paths are relative to the target Flutter project. Resolve sibling skills through the installed skill registry (or sibling directories), never by assuming a skills/ folder in the application. If a required dependency is absent, name it and report the affected step as unavailable; never invent its rules or claim complete coverage.

Pattern References

For complex Riverpod scenarios, read the relevant pattern file before writing any code:

PatternFile
StreamProvider overrides (AsyncData vs Stream.value)patterns/stream-provider-overrides.md
Notifier whose build() watches a StreamProviderpatterns/notifier-with-stream-deps.md
Computed provider that returns AsyncValue<T> synchronouslypatterns/computed-async-value-providers.md
Fixture helper functions and makeContainer factorypatterns/fixture-helpers.md
FutureProvider error paths and container.pump()patterns/future-provider-error-paths.md
Pre-stub non-nullable returns (Stream<T>, Future<String>)patterns/prestub-nonnullable-returns.md
verify() + verifyInOrder() clash in mocktail 1.0.xpatterns/verify-verifyinorder-antipattern.md
Notifier with internal ref.listen in action methodpatterns/notifier-with-internal-ref-listen.md
Adversarial edge-case catalog per input typepatterns/edge-case-catalog.md — read before Phase 7, always
Test quality gate (anti-tautology, mutation mindset)patterns/test-quality-gate.md — read before Phase 9.5, always

Phase 0 — Testability Check

Run only when the argument is a single `.dart` file. Skip if the argument is a feature folder.

Read the file and classify:

SignalDecision
extends StatelessWidget / StatefulWidget / ConsumerWidget / StateStop — belongs to widget tests. Tell the user.
Filename ends in .g.dart or .freezed.dartStop — generated code, never hand-tested.
Top-level class is abstract with no factory constructorStop — not instantiable; test concrete subclasses.
All collaborators injected via constructor or providerProceed
Directly instantiates FirebaseFirestore / FirebaseAuth without injectionWarn — hard to unit-test; suggest refactoring or integration test. Offer to test what is feasible.

Phase 1 — Gap Detection

If a test file already exists for the target, read it first.

  1. Read the source — list every public method, factory constructor, computed getter, thrown exception.
  2. Read the existing test — extract all group(...) and test(...) names.
  3. Diff: methods with no group → create it. Methods with a group but missing branches → add the missing test(...) inside. Exception classes with no property tests → add an exception group (Phase 6).
  4. Append new group blocks at the end of main(). Never restructure existing tests.

If no test file exists, skip to Phase 2.


Phase 2 — Discovery

Before writing a line of test code:

  1. Read the target file(s) — every public API, constructor param, dependency, thrown exception.
  2. Read the central mocks file — apps/pollicino_viewer/test/src/mocks.dart. Reuse every mock that exists there.
  3. Grep sibling test files — test/src/features/<feature>/ — for locally declared mocks.
  4. For each dependency: does class Mock<Dep> already exist? Use it; never redeclare.
Rule: grep first. grep -r "implements FooRepository" apps/pollicino_viewer/test/

When scanning a feature folder, exclude from scope:

  • presentation/ — widget tests, out of scope
  • *.g.dart, *.freezed.dart — generated
  • Abstract repository interfaces — test via the concrete mock in service tests

Prioritise in this order:

  1. Domain models (entities, value objects, exceptions)
  2. Pure utilities / helpers
  3. Application services with few deps
  4. Riverpod Notifiers / AsyncNotifiers / Controllers
  5. Repository implementations only if a FakeFirestore in-memory fake is feasible

Skip with stated reason: Firebase repos requiring real network, widgets, pure DTOs with zero logic, trivial getters/setters with no logic, classes whose only behavior is delegating a call to an injected dependency (a test there verifies the mock, not the subject).


Phase 3 — File Location + Header

Mirror lib/ exactly under test/src/:

lib/src/features/foo/application/foo_service.dart
→ test/src/features/foo/application/foo_service_test.dart

Every test file starts with:

dart
@Timeout(Duration(seconds: 5))
library;
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
// feature imports...
// Always this relative path from test/src/features/<feature>/<layer>/
import '../../../mocks.dart';
// Local mocks — only what doesn't exist in mocks.dart
class MockFooRepository extends Mock implements FooRepository {}
  • @Timeout + library; — always, in that order.
  • Use // at library level, never /// (triggers dangling_library_doc_comments lint).
  • Listener<T> is already in mocks.dart — import it, never redeclare.

Central mocks policy: add a mock to mocks.dart only when used by 2+ different features. Single-feature mocks stay in their own test file.


Phase 4 — Mocktail Strategy

Use mocktail exclusively. Never use mockito even if legacy .mocks.dart files exist nearby.

dart
late MockFooRepository mockRepo;
setUpAll(() {
registerFallbackValue(FooEntity.empty()); // required for every type passed to any() / captureAny()
});
setUp(() => mockRepo = MockFooRepository());
tearDown(() => reset(mockRepo));
dart
// Stub
when(() => mockRepo.getItems()).thenAnswer((_) async => [item]);
when(() => mockRepo.watch()).thenAnswer((_) => Stream.value([item]));
when(() => mockRepo.doVoid()).thenAnswer((_) async {});
// Verify
verify(() => mockRepo.save(any())).called(1);
verifyNever(() => mockRepo.delete(any()));
// Capture
final captured = verify(() => mockRepo.save(captureAny()))
.captured.single as FooEntity;
Pre-stub non-nullable returns — REQUIRED
See patterns/prestub-nonnullable-returns.md for full explanation.

when() evaluates its closure synchronously, calling the mock before the stub is registered. For methods returning Stream<T>, Future<String>, or any non-nullable type, the unregistered mock returns null and Dart's sound null-safety throws a TypeError immediately — corrupting mocktail's state for subsequent tests.

Rule: in setUp(), stub every method that returns a non-nullable type with a safe default, before any test-specific when():

dart
setUp(() {
mockRepo = MockFooRepository();
when(() => mockRepo.sendOrder(any())).thenAnswer((_) async => ''); // Future<String>
when(() => mockRepo.watchOrder(any())).thenAnswer((_) => const Stream.empty()); // Stream<T>
});

For named parameters use any(named: 'paramName'):

dart
when(
() => mockService.sendStopOrder(scenarioId: any(named: 'scenarioId')),
).thenAnswer((_) async => '');
verify() + verifyInOrder() — do not mix
See patterns/verify-verifyinorder-antipattern.md for full explanation.

In mocktail 1.0.x, calling verify() on a mock before verifyInOrder() on the same mock marks all recorded calls as [VERIFIED], leaving nothing for verifyInOrder to match.

Rule: never mix both in the same test. For order assertions use only verifyInOrder. For count assertions use only verify. For AsyncNotifier final state — skip Listener entirely and assert container.read(provider) directly.


Phase 5 — Riverpod 3.x Patterns

Container
dart
// Preferred — auto-disposes, no addTearDown needed
final container = ProviderContainer.test(overrides: [...]);
// Legacy — keep in existing files that already use it
final container = ProviderContainer();
addTearDown(container.dispose);
Override strategy table
SituationOverride
Simple provider (non-notifier)provider.overrideWithValue(mock)
Replace whole Notifierprovider.overrideWith(MockNotifier.new)
Seed state, keep real methodsprovider.overrideWithBuild((ref) => state)
Testing StreamProvider itselfprovider.overrideWith((ref) => Stream.value(v)) — starts AsyncLoading, must await
Computed provider consuming streamstreamDep.overrideWithValue(AsyncData(v)) — synchronous, no await
For StreamProvider and Notifier-with-stream-deps patterns, read the pattern files listed above.
Sync Notifier
dart
final container = ProviderContainer.test();
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
AsyncNotifier — happy path
dart
when(() => mockRepo.fetchFoo('1')).thenAnswer((_) async => expectedFoo);
final container = ProviderContainer.test(
overrides: [fooRepositoryProvider.overrideWithValue(mockRepo)],
);
await container.read(fooProvider.notifier).loadFoo('1');
final state = container.read(fooProvider);
expect(state, isA<AsyncData<Foo>>());
expect(state.requireValue, expectedFoo);
State transition spy
dart
final states = <AsyncValue<Foo>>[];
container.listen<AsyncValue<Foo>>(
fooProvider,
(_, next) => states.add(next),
fireImmediately: true,
);
await container.read(fooProvider.notifier).loadFoo('1');
expect(states, [isA<AsyncLoading<Foo>>(), isA<AsyncData<Foo>>()]);

For call-count assertions use Listener<T> from mocks.dart:

dart
final listener = Listener<AsyncValue<Foo>>();
container.listen(fooProvider, listener.call, fireImmediately: true);
verify(() => listener(any(), isA<AsyncData<Foo>>())).called(1);
Direct stream testing

When the class under test exposes a .stream property directly (not via a Riverpod provider), call expectLater before the action — values already emitted cause a 30-second timeout:

dart
// CORRECT — subscribe before triggering emissions; do NOT await this line
expectLater(
controller.stream,
emitsInOrder([
const AsyncLoading<void>(),
const AsyncData<void>(null),
]),
);
await controller.doAction(); // emissions happen here

When you cannot match all properties of an emitted value (e.g. AsyncError has an unpredictable stack trace), use a predicate:

dart
expectLater(
controller.stream,
emitsInOrder([
const AsyncLoading<void>(),
predicate<AsyncValue<void>>((value) {
expect(value, isA<AsyncError<void>>());
return true;
}),
]),
);
Prefer container.listen (state transition spy above) for Riverpod providers. Use direct stream testing only when the class exposes .stream independently of any provider.
Keep autoDispose provider alive
dart
final sub = container.listen(fooProvider, (_, __) {});
addTearDown(sub.close);
expect(sub.read(), expected);
Family provider
dart
container.read(fooProvider('id').notifier).doSomething();
// Isolation: one family instance must not affect another
expect(container.read(fooProvider('id-1')), expectedForId1);
expect(container.read(fooProvider('id-2')), defaultState);
For FutureProvider error paths (AsyncError, container.pump()), read patterns/future-provider-error-paths.md.
Notifier with internal ref.listen in an action method
See patterns/notifier-with-internal-ref-listen.md for full explanation.

When a Notifier calls ref.listen(someStreamProvider(id), callback) inside an action (not in build()), the stream subscription is created on-demand. To test state transitions:

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/iamantoniodinuzzo/claude-flutter/unit-test/badge)](https://verified-skill.com/skills/iamantoniodinuzzo/claude-flutter/unit-test)

Something wrong with this skill or its page? Tell us.