dart test
- Dart course
- Intermediate
- Lesson 82/116
- 5 min
Learn the dart test framework.
The dart test framework
dart test is Dart's built-in test framework. Tests live in the test/ folder with the *_test.dart extension. They run from the command line with dart test.
A test file starts with import 'package:test/test.dart';. Each test is written as test('description', () { ... }). Inside it you make claims with expect.
Tests verify that your code behaves as expected. A wrong change turns a test red, so you catch the error early.
The test file skeleton
A test file skeleton looks like this: it starts with import 'package:test/test.dart';, then test('addition', () { expect(2 + 3, equals(5)); });. Here expect compares the actual and expected values.
equals(5) is a matcher. The expected value is 5; the actual value is 2 + 3 = 5. If equal the test is green, otherwise red.
Each test should be short and probe one behavior. The description tells what is being probed.
Practice The Calculator class
Define a Calculator class with a method int add(int a, int b) => a + b;. In main print the result of Calculator().add(2, 3) with print.
Starter code
// Define the Calculator class, add the add method
void main() {
// print the result of add(2, 3)
}Sample solution
class Calculator {
int add(int a, int b) => a + b;
}
void main() {
print(Calculator().add(2, 3));
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the dart test command run?
- The lib/ folder
- pubspec.yaml
- The bin/ folder
- The *_test.dart files in test/ Correct answer
Explanation: dart test runs the *_test.dart files inside test/.
2 Import the test package
import 'package:test/____.dart';
import 'package:test/test.dart';
Explanation: the test package is imported as 'package:test/test.dart'.
3 Test file parts
| Term | Meaning |
|---|---|
test/ |
Test folder |
*_test.dart |
Test file name |
import 'package:test/test.dart' |
Import |
test('...', () {}) |
Test block |