Integration tests
- Dart course
- Expert
- Lesson 37/47
- 5 min
Learn to write integration tests.
Integration tests
An integration test verifies that multiple components work together. While a unit test isolates a single function, an integration test exercises the whole flow.
In Dart the integration_test package runs in a real environment. Widget tests use testWidgets; the end-to-end flow is exercised.
Advantage: catches integration bugs between components. Disadvantage: slower than unit tests. Therefore few integration, many unit tests are recommended.
Expectations and setup
The building block of tests is the expect(actual, expected) assertion. setUp runs before each test, tearDown after each test.
In integration tests setUp can start a real database or HTTP server. This makes the test realistic but slower.
group('addition', () { ... }) groups related tests. A separate setUp can be written per group; this organizes tests neatly.
Practice Define a Calculator and an expect
Define a Calculator class with int add(int a, int b) => a + b;. Define a void expect(dynamic actual, dynamic expected, String label) function with body { if (actual == expected) { print('PASS: $label'); } else { print('FAIL: $label'); } }. In main create final calc = Calculator(); and call expect(calc.add(2, 3), 5, 'add');.
Starter code
void main() {
// define a Calculator class (add method)
// define an expect function (prints PASS/FAIL)
// create a Calculator; call expect for add(2,3)
}Sample solution
class Calculator {
int add(int a, int b) => a + b;
}
void expect(dynamic actual, dynamic expected, String label) {
if (actual == expected) {
print('PASS: $label');
} else {
print('FAIL: $label');
}
}
void main() {
final calc = Calculator();
expect(calc.add(2, 3), 5, 'add');
}Expected output
PASS: add
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does an integration test verify?
- A single function
- That components work together Correct answer
- One line of code
- Only imports
Explanation: an integration test verifies a multi-component flow.
2 The test function
void main() {
____('addition works', () {
expect(2 + 3, 5);
});
}
void main() {
test('addition works', () {
expect(2 + 3, 5);
});
}
Explanation: test(...) declares a test.
3 Match the test parts
| Term | Meaning |
|---|---|
integration_test |
Package |
testWidgets |
Widget test |
expect |
Assertion |
setUp |
Setup |