test and expect
- Dart course
- Intermediate
- Lesson 83/116
- 5 min
Learn assertions with test and expect.
test and expect
test('name', () { ... }) opens a test block. Inside it you make claims with expect(actual, matcher). For example expect(square(4), equals(16)) probes the square function.
Matchers include equals(x), isTrue, isFalse and throwsException. Each checks a different condition.
A test can hold several expect calls. If the first fails the test stops and the rest do not run.
Matchers
Matchers check different conditions. equals(x) tests equality, isTrue truth, isFalse falsity, throwsException error throwing.
For example expect(parse('x'), throwsFormatException) expects an error. If the error is thrown the test is green; otherwise red.
Matchers make a test readable. expect(x, isNotNull) reads more clearly than expect(x == null, isFalse).
Practice The square function
Write a function int square(int n) => n * n;. In main print the result of square(4) with print.
Starter code
// Define the square function
void main() {
// print the result of square(4)
}Sample solution
int square(int n) => n * n;
void main() {
print(square(4));
}Expected output
16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does expect(actual, expected) do?
- Compares actual and expected values Correct answer
- Opens a file
- Sets up a loop
- Throws an error
Explanation: expect compares the actual and expected values.
2 The expect call
expect(square(4), ____(16));
expect(square(4), equals(16));
Explanation: equals(16) states the expected value.
3 What does throwsException probe?
- Value equality
- That an error is thrown Correct answer
- End of a loop
- Existence of a file
Explanation: throwsException probes that an error is thrown.