Claude
Skills
Sign in
Back

flutter-core:flutter-testing-quality

Included with Lifetime
$97 forever

Comprehensive Flutter testing and quality assurance guidance covering unit testing, widget testing, integration testing, golden tests, debugging techniques, code coverage, test-driven development, mocking strategies, DevTools profiling, and quality metrics. Use when testing Flutter applications, writing unit tests, widget tests, integration tests, debugging issues, improving test coverage, creating golden files, mocking dependencies, profiling performance, or establishing testing strategies.

Writing & Docs

What this skill does


# Flutter Testing & Quality

A comprehensive guide to testing and quality assurance in Flutter applications. This skill covers the complete testing pyramid from fast unit tests to comprehensive integration tests, along with debugging techniques, profiling strategies, and quality metrics that ensure your Flutter apps are reliable, maintainable, and performant.

## Philosophy: Testing as a First-Class Citizen

Flutter's testing framework is not an afterthought—it's a core part of the development experience. The framework provides excellent testing APIs that make it genuinely pleasant to write tests. Testing in Flutter follows the testing pyramid: many fast unit tests at the base, a moderate number of widget tests in the middle, and fewer but crucial integration tests at the top.

The key insight is that testing isn't just about catching bugs—it's about designing better APIs, improving code architecture, and giving you confidence to refactor and evolve your codebase. Well-tested Flutter apps are easier to maintain, onboard new developers to, and extend with new features.

## Understanding the Testing Pyramid

Flutter supports three types of tests, each serving a distinct purpose in your quality assurance strategy.

### Unit Tests

Unit tests validate individual functions, methods, and classes in isolation. They are the foundation of your testing strategy because they:

- Run extremely fast (thousands can execute in seconds)
- Provide precise failure messages pointing to exact issues
- Enable test-driven development workflows
- Validate business logic independently of Flutter framework
- Require no special Flutter environment

Unit tests should comprise 60-70% of your test suite. They test pure Dart code: data models, utility functions, business logic, validators, parsers, and state management logic.

### Widget Tests

Widget tests (also called component tests) validate that your UI widgets behave correctly. They:

- Test widgets in isolation from the full app
- Verify widget rendering, layout, and user interactions
- Run faster than integration tests but slower than unit tests
- Can pump widgets, trigger interactions, and verify results
- Use Flutter's testing framework to simulate the widget tree

Widget tests should comprise 20-30% of your test suite. They test individual screens, complex widgets, form behavior, animations, and user interactions without requiring a real device.

### Integration Tests

Integration tests validate complete app flows on real devices or simulators. They:

- Test the entire app as users would experience it
- Verify navigation flows, API integration, and persistence
- Run slowest but provide highest confidence
- Catch issues that unit and widget tests miss
- Require actual device/emulator to execute

Integration tests should comprise 5-10% of your test suite. They test critical user journeys, onboarding flows, checkout processes, and cross-cutting concerns.

## Decision Tree: Choosing the Right Test Type

Use this decision tree to select the appropriate testing approach:

### Question 1: Does it involve UI rendering?

**If NO (pure Dart logic):**
→ Use **Unit Tests**
→ Test with `test()` package
→ No Flutter dependencies needed
→ **Reference**: [Unit Testing](references/unit-testing.md)

**If YES (involves widgets):**
→ Continue to Question 2

### Question 2: Does it require navigation or multiple screens?

**If NO (single widget/screen):**
→ Use **Widget Tests**
→ Test with `testWidgets()`
→ Mock external dependencies
→ **References**: [Widget Testing](references/widget-testing.md), [Mocking Strategies](examples/mocking-strategies.md)

**If YES (multiple screens/full flows):**
→ Use **Integration Tests**
→ Test with `integration_test` package
→ Run on real device/emulator
→ **Reference**: [Integration Testing](references/integration-testing.md)

### Question 3: Do you need visual regression testing?

**If validating pixel-perfect UI:**
→ Use **Golden Tests**
→ Generate golden files for comparison
→ Catch unintended visual changes
→ **Reference**: [Golden Tests](references/golden-tests.md)

## Core Testing Principles

Regardless of which test type you choose, follow these principles:

### 1. Arrange-Act-Assert (AAA) Pattern

Structure every test in three clear phases:

```dart
test('counter increments correctly', () {
  // Arrange: Set up test conditions
  final counter = Counter(initialValue: 0);

  // Act: Execute the operation
  counter.increment();

  // Assert: Verify the result
  expect(counter.value, 1);
});
```

This pattern makes tests readable, maintainable, and easy to debug when they fail.

### 2. Test One Thing at a Time

Each test should verify a single behavior or condition. If a test fails, you should immediately know what broke:

```dart
// Good: Tests one specific behavior
test('login validates empty email', () {
  final result = validator.validateEmail('');
  expect(result, 'Email cannot be empty');
});

// Bad: Tests multiple unrelated things
test('login validation', () {
  expect(validator.validateEmail(''), 'Email cannot be empty');
  expect(validator.validatePassword(''), 'Password cannot be empty');
  expect(validator.validateEmail('invalid'), 'Invalid email format');
});
```

### 3. Make Tests Independent

Tests should not depend on execution order or shared state. Each test should set up its own data and clean up after itself:

```dart
// Use setUp and tearDown for test isolation
group('UserRepository', () {
  late UserRepository repository;
  late Database mockDatabase;

  setUp(() {
    mockDatabase = MockDatabase();
    repository = UserRepository(mockDatabase);
  });

  tearDown(() {
    mockDatabase.close();
  });

  test('saves user correctly', () {
    // Test implementation
  });
});
```

### 4. Use Descriptive Test Names

Test names should describe what is being tested and the expected outcome:

```dart
// Good: Clear and descriptive
test('formatCurrency converts dollars to formatted string with two decimals', () {});
test('submitForm shows error message when email is invalid', () {});

// Bad: Vague and unclear
test('test1', () {});
test('currency works', () {});
```

### 5. Test Edge Cases and Error Conditions

Don't just test the happy path. Test boundary conditions, null values, empty lists, network failures, and error states:

```dart
group('parseUserAge', () {
  test('returns age for valid input', () {
    expect(parseUserAge('25'), 25);
  });

  test('returns null for negative numbers', () {
    expect(parseUserAge('-5'), null);
  });

  test('returns null for non-numeric input', () {
    expect(parseUserAge('abc'), null);
  });

  test('returns null for null input', () {
    expect(parseUserAge(null), null);
  });
});
```

## Testing Strategy for Different App Components

### Testing State Management

State management logic should be thoroughly unit tested independently of widgets:

- **setState**: Test stateful widgets with widget tests
- **ChangeNotifier/ValueNotifier**: Unit test notifier logic, widget test UI integration
- **Provider/Riverpod**: Mock providers in widget tests
- **BLoC**: Unit test blocs/cubits, widget test UI with BlocProvider
→ **Cross-reference**: flutter-state-management skill

### Testing Navigation and Routing

Navigation requires widget or integration tests:

- Widget tests: Mock Navigator and verify navigation calls
- Integration tests: Test complete navigation flows
- Verify route transitions, deep linking, and route guards
→ **Cross-reference**: flutter-navigation-routing skill

### Testing Network Calls

Network integration requires mocking:

- Unit test: Mock HTTP clients and test response handling
- Widget test: Mock repositories providing data
- Integration test: Use real API or mock server
→ **References**: [Unit Testing](references/unit-testing.md), [Mocking Strategies](examples/mocking-strategies.md)

### Testing Persistence

Database and storage operations require isolation:

- Unit test: Mock database interfaces
- Widget test: Provide test d

Related in Writing & Docs