Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问clear审计通过

flutter-testingFlutter 测试

Agent Skill

用于辅助测试设计、自动化测试、用例整理和回归验证。它适合让 Agent 编写单元测试、端到端测试、测试计划或根据失败日志定位问题。使用时需要确认项目测试框架、运行命令和夹具数据,避免为了通过测试而改坏真实逻辑;涉及浏览器或外部服务时,应区分本地模拟、测试环境和生产环境。

总安装

29,952

周安装

1,174

GitHub Stars

92

下载量

9,696
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:flutter-testing(Flutter 测试)
来源仓库:https://github.com/madteacher/mad-agents-skills
仓库路径:skills/flutter-testing
安装命令:
npx skills add https://github.com/madteacher/mad-agents-skills --skill flutter-testing
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/madteacher/mad-agents-skills --skill flutter-testing

简介

针对 Flutter 应用程序的单元、小部件和集成测试的综合指南。

  • 涵盖三种测试类型并进行权衡分析:独立逻辑的单元测试(快速、低维护)、UI 组件的小部件测试(置信度更高、依赖性更强)以及端到端流程的集成测试(置信度最高、执行速度最慢)
  • 包括所有三个测试类别的实际示例,从基本的计数器测试到复杂的用户流程和性能分析
  • 为插件交互、平台通道处理和外部依赖项提供模拟策略,以保持测试可靠和快速
  • 通过具体的解决方案和预防模式解决常见的测试错误(RenderFlex 溢出、无界视口、构建期间的 setState)
  • 通过覆盖率报告和调试技术涵盖不同构建模式(调试、配置文件、发布)和平台(Android、iOS、Web)的测试执行

SKILL.md

Flutter Testing

Overview

This skill provides comprehensive guidance for testing Flutter applications across all test types. Flutter testing falls into three categories:

  • Unit tests - Test individual functions, methods, or classes in isolation
  • Widget tests (component tests) - Test single widgets and verify UI appearance and behavior
  • Integration tests - Test complete apps or large parts to verify end-to-end functionality

A well-tested Flutter app has many unit and widget tests for code coverage, plus enough integration tests to cover important use cases.

Test Type Trade-offs

TradeoffUnitWidgetIntegration
ConfidenceLowHigherHighest
Maintenance costLowHigherHighest
DependenciesFewMoreMost
Execution speedQuickQuickSlow

Build Modes for Testing

Flutter supports three build modes with different implications for testing:

  • Debug mode - Use during development with hot reload. Assertions enabled, debugging enabled, but performance is janky
  • Profile mode - Use for performance analysis. Similar to release mode but with some debugging features enabled
  • Release mode - Use for deployment. Assertions disabled, optimized for speed and size

Quick Start

Unit Tests

Unit tests test a single function, method, or class. Mock external dependencies and avoid disk I/O or UI rendering.

import 'package:test/test.dart';
import 'package:my_app/counter.dart';

void main() {
  test('Counter value should be incremented', () {
    final counter = Counter();
    counter.increment();
    expect(counter.value, 1);
  });
}

Run with: flutter test

Widget Tests

Widget tests test single widgets to verify UI appearance and interaction.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('MyWidget has a title and message', (tester) async {
    await tester.pumpWidget(const MyWidget(title: 'T', message: 'M'));

    final titleFinder = find.text('T');
    final messageFinder = find.text('M');

    expect(titleFinder, findsOneWidget);
    expect(messageFinder, findsOneWidget);
  });
}

Integration Tests

Integration tests test complete apps on real devices or emulators.

import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main.dart';

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('tap button, verify counter', (tester) async {
    await tester.pumpWidget(const MyApp());
    expect(find.text('0'), findsOneWidget);

    await tester.tap(find.byKey(const ValueKey('increment')));
    await tester.pumpAndSettle();

    expect(find.text('1'), findsOneWidget);
  });
}

Run with: flutter test integration_test/

Testing Workflow Decision Tree

  1. What are you testing?

- Single function/class → Unit Tests - Single widget/component → Widget Tests - Complete user flow → Integration Tests

  1. Does it depend on plugins/native code?

- Yes → See Plugins in Tests or Testing Plugins

  1. Need to mock dependencies?

- Yes → See Mocking Guide

  1. Encountering errors?

- See Common Testing Errors

Unit Tests

Unit tests verify the correctness of a unit of logic under various conditions.

When to Use Unit Tests

  • Testing business logic functions
  • Validating data transformations
  • Testing state management logic
  • Mocking external services/API calls

Key Concepts

  • Use package:test/test.dart
  • Mock dependencies using Mockito or similar
  • Avoid file I/O or UI rendering
  • Fast execution, high maintainability

Advanced Unit Testing

For mocking dependencies, plugin interactions, and complex scenarios, see Unit Testing Reference.

Widget Tests

Widget tests verify widget UI appearance and behavior in a test environment.

When to Use Widget Tests

  • Testing widget rendering
  • Verifying user interactions (taps, drags, scrolling)
  • Testing different orientations
  • Validating widget state changes

Widget Testing Patterns

Finding Widgets

// By text
final titleFinder = find.text('Title');

// By widget type
final buttonFinder = find.byType(ElevatedButton);

// By key
final fabFinder = find.byKey(const ValueKey('increment'));

// By widget instance
final myWidgetFinder = find.byWidget(myWidgetInstance);

User Interactions

// Tap
await tester.tap(buttonFinder);

// Drag
await tester.drag(listFinder, const Offset(0, -300));

// Enter text
await tester.enterText(fieldFinder, 'Hello World');

// Scroll
await tester.fling(listFinder, const Offset(0, -500), 10000);
await tester.pumpAndSettle();

Testing Different Orientations

testWidgets('widget in landscape mode', (tester) async {
  // Set to landscape
  await tester.binding.setSurfaceSize(const Size(800, 400));
  await tester.pumpWidget(const MyApp());

  // Verify landscape behavior
  expect(find.byType(MyWidget), findsOneWidget);

  // Reset to portrait
  addTearDown(tester.binding.setSurfaceSize(null));
});

Advanced Widget Testing

For scrolling, complex interactions, and performance testing, see Widget Testing Reference.

Integration Tests

Integration tests test complete apps or large parts on real devices or emulators.

When to Use Integration Tests

  • Testing complete user flows
  • Verifying multiple screens/pages
  • Testing navigation flows
  • Performance profiling

Integration Test Structure

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  group('end-to-end test', () {
    testWidgets('complete user flow', (tester) async {
      await tester.pumpWidget(const MyApp());

      // Step 1: Navigate to screen
      await tester.tap(find.text('Login'));
      await tester.pumpAndSettle();

      // Step 2: Enter credentials
      await tester.enterText(find.byKey(const Key('username')), 'user');
      await tester.enterText(find.byKey(const Key('password')), 'pass');

      // Step 3: Submit
      await tester.tap(find.text('Submit'));
      await tester.pumpAndSettle();

      // Verify result
      expect(find.text('Welcome'), findsOneWidget);
    });
  });
}

Performance Testing

testWidgets('scrolling performance', (tester) async {
  await tester.pumpWidget(const MyApp());

  final listFinder = find.byType(ListView);

  // Measure performance
  final timeline = await tester.trace(() async {
    await tester.fling(listFinder, const Offset(0, -500), 10000);
    await tester.pumpAndSettle();
  });

  // Analyze timeline data
  expect(timeline.frames.length, greaterThan(10));
});

Advanced Integration Testing

For performance profiling, CI integration, and complex scenarios, see Integration Testing Reference.

Plugins in Tests

When testing code that uses plugins, special handling is required to avoid crashes.

Testing App Code with Plugins

If your Flutter app uses plugins, you need to mock the platform channel calls in unit/widget tests.

import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  setUp(() {
    // Mock platform channel
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
        .setMockMethodCallHandler(
      const MethodChannel('your.plugin.channel'),
      (MethodCall methodCall) async {
        if (methodCall.method == 'getPlatformVersion') {
          return 'Android 12';
        }
        return null;
      },
    );
  });

  tearDown(() {
    TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
        .setMockMethodCallHandler(
      const MethodChannel('your.plugin.channel'),
      null,
    );
  });
}

Testing Plugins

For comprehensive guidance on testing Flutter plugins (including native code), see Plugin Testing Reference.

Common Testing Errors

'A RenderFlex overflowed...'

Yellow and black stripes indicate overflow. Usually caused by unconstrained children in Row/Column.

Solution: Wrap the overflowing widget in Expanded or Flexible.

// Problem
Row(
  children: [
    Icon(Icons.message),
    Column(children: [Text('Very long text...')]), // Overflow!
  ],
)

// Solution
Row(
  children: [
    Icon(Icons.message),
    Expanded(child: Column(children: [Text('Very long text...')])),
  ],
)

'Vertical viewport was given unbounded height'

Occurs when ListView (or other scrollable) is inside Column without height constraints.

Solution: Wrap in Expanded or use shrinkWrap: true.

// Problem
Column(
  children: [
    Text('Header'),
    ListView(children: [...]), // Error!
  ],
)

// Solution
Column(
  children: [
    Text('Header'),
    Expanded(child: ListView(children: [...])),
  ],
)

'setState called during build'

Never call setState during build method.

Solution: Use Navigator API or defer to post-build callback.

For more errors and solutions, see Common Errors Reference.

Testing Best Practices

  1. Test Pyramid - More unit/widget tests, fewer integration tests
  2. Descriptive Test Names - Names should clearly describe what and why
  3. Arrange-Act-Assert - Structure tests with clear sections
  4. Avoid Test Interdependence - Each test should be independent
  5. Mock External Dependencies - Keep tests fast and reliable
  6. Run Tests in CI - Automate testing on every push

Running Tests

Run All Tests

flutter test

Run Specific Test File

flutter test test/widget_test.dart

Run Integration Tests

flutter test integration_test/

Run with Coverage

flutter test --coverage
genhtml coverage/lcov.info -o coverage/html
open coverage/html/index.html

Run Tests on Different Platforms

# Android
flutter test --platform android

# iOS
flutter test --platform ios

# Web
flutter test --platform chrome

Debugging Tests

Debug a Test

flutter test --no-sound-null-safety test/my_test.dart

Verbose Output

flutter test --verbose

Run Specific Test

flutter test --name "Counter value should be incremented"

Resources

Reference Files

External Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

27.1%
按下载量换算2,628

OpenCode

23.03%
按下载量换算2,233

Gemini CLI

17.84%
按下载量换算1,730

Antigravity

12.79%
按下载量换算1,240

Codex

7.45%
按下载量换算722

Cursor

3.44%
按下载量换算334

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills