Introduction _ Flutter
Introduction _ Flutter
Learn more
Contents
1. Add the test dependency
2. Create a test file
3. Create a class to test
4. Write a test for our class
5. Combine multiple tests in a group
6. Run the tests
Run tests using IntelliJ or VSCode
Run tests in a terminal
How can you ensure that your app continues to work as you add more features or change
existing functionality? By writing tests.
Unit tests are handy for verifying the behavior of a single function, method, or class. The
test package provides the core framework for writing unit tests, and the flutter_test
package provides additional utilities for testing widgets.
This recipe demonstrates the core features provided by the test package using the
following steps:
For more information about the test package, see the test package documentation.
The counter.dart file contains a class that you want to test and resides in the lib
folder. The counter_test.dart file contains the tests themselves and lives inside the
test folder.
In general, test files should reside inside a test folder located at the root of your Flutter
application or package. Test files should always end with _test.dart , this is the
convention used by the test runner when searching for tests.
When you're finished, the folder structure should look like this:
counter_app/
lib/
counter.dart
test/
counter_test.dart
dart
class Counter {
int value = 0;
dart
// Import the test package and Counter class
import 'package:counter_app/counter.dart';
import 'package:test/test.dart';
void main() {
test('Counter value should be incremented', () {
final counter = Counter();
counter.increment();
expect(counter.value, 1);
});
}
dart
import 'package:counter_app/counter.dart';
import 'package:test/test.dart';
void main() {
group('Test start, increment, decrement', () {
test('value should start at 0', () {
expect(Counter().value, 0);
});
expect(counter.value, 1);
});
counter.decrement();
expect(counter.value, -1);
});
});
}
IntelliJ
VSCode
To run all tests you put into one group , run the following command from the root of the
project:
To learn more about unit tests, you can execute this command:
Except as otherwise noted, this site is licensed under a Creative Commons Attribution 4.0 International
License, and code samples are licensed under the 3-Clause BSD License.