How to Write Tests in Flutter: Syntax and Examples
To write tests in Flutter, use the
test package and create test functions with test() that include expectations using expect(). Run tests with flutter test to verify your app's behavior.Syntax
Flutter tests use the test function to define a test case. Inside it, you write code to set up conditions and use expect() to check results. The group() function helps organize related tests.
dart
import 'package:flutter_test/flutter_test.dart'; void main() { group('String tests', () { test('Check if string contains substring', () { var text = 'hello flutter'; expect(text.contains('flutter'), true); }); }); }
Example
This example shows a simple test that checks if a string contains a specific word. It demonstrates how to write a test case and use expect() to verify the condition.
dart
import 'package:flutter_test/flutter_test.dart'; void main() { test('String contains flutter', () { var greeting = 'Welcome to flutter testing'; expect(greeting.contains('flutter'), true); }); }
Output
00:00 +1: All tests passed!
Common Pitfalls
Common mistakes include forgetting to import flutter_test, not wrapping tests inside main(), or using expect() incorrectly. Also, avoid running UI code outside widget tests.
dart
import 'package:flutter_test/flutter_test.dart'; void main() { // Wrong: missing test() function // expect(1 + 1, 2); // Right: test('Simple addition', () { expect(1 + 1, 2); }); }
Quick Reference
- test(): Defines a single test case.
- expect(actual, matcher): Checks if actual value meets the matcher.
- group(): Organizes multiple tests.
- flutter test: Command to run tests.
Key Takeaways
Use the test() function to write individual test cases in Flutter.
Use expect() to verify that your code behaves as expected.
Organize tests with group() for better structure.
Always import flutter_test package to access testing functions.
Run tests using the flutter test command in your terminal.