How to Use Flutter Test Command: Syntax, Example, and Tips
Use the
flutter test command in your terminal to run all tests in the test/ directory of your Flutter project. This command executes unit and widget tests and shows results in the console, helping you verify your app's behavior.Syntax
The basic syntax of the flutter test command is simple:
flutter test [options] []
Here, [options] are optional flags to customize the test run, and [<test-file>] lets you run a specific test file instead of all tests.
bash
flutter test flutter test test/widget_test.dart flutter test --coverage
Example
This example shows a simple unit test in Flutter and how to run it using flutter test. The test checks if a function returns the expected string.
dart
import 'package:flutter_test/flutter_test.dart'; String greet() => 'Hello Flutter!'; void main() { test('greet returns correct string', () { expect(greet(), 'Hello Flutter!'); }); }
Output
00:00 +1: All tests passed!
Process finished with exit code 0
Common Pitfalls
Some common mistakes when using flutter test include:
- Running the command outside the Flutter project directory, causing no tests to be found.
- Not importing
flutter_testpackage in test files, leading to errors. - Trying to test code that depends on Flutter widgets without using
WidgetTesteror proper setup.
Always ensure your test files are inside the test/ folder and named with _test.dart suffix.
dart
/* Wrong: test file outside test/ folder or missing flutter_test import */ /* Right: */ import 'package:flutter_test/flutter_test.dart'; void main() { test('example test', () { expect(1 + 1, 2); }); }
Quick Reference
Here is a quick cheat sheet for the flutter test command:
| Command | Description |
|---|---|
| flutter test | Runs all tests in the test/ directory |
| flutter test test/my_test.dart | Runs a specific test file |
| flutter test --coverage | Runs tests and collects code coverage |
| flutter test --name 'test name' | Runs tests matching the given name pattern |
| flutter test --machine | Outputs test results in machine-readable JSON format |
Key Takeaways
Run
flutter test inside your Flutter project to execute all tests in the test/ folder.Test files must be named with
_test.dart and import flutter_test package.Use options like
--coverage or --name to customize test runs.Keep test files inside the test/ directory to be detected by the command.
Check console output for test results and fix any errors shown.