group
- Dart course
- Intermediate
- Lesson 84/116
- 5 min
Learn test organization with group.
Organization with group
group('name', () { ... }) gathers related tests. For example you place the tests of a MathUtils class inside group('MathUtils', () { ... }).
Groups organize test output; each test appears with its group name. This makes large test files easy to read.
Groups can nest. group('Math', () { group('factorial', () { ... }); }) creates a subgroup.
Nested groups
Groups can nest. For example group('Math', () { group('factorial', () { test('zero', () {}); }); }) builds a hierarchy. The output shows Math factorial zero.
Inner groups inherit the outer group's context. A setUp defined in the outer group also runs for the inner group's tests.
But very deep nesting hurts readability. Two levels are usually enough.
Practice MathUtils and factorial
Define a MathUtils class with a static int factorial(int n) method. If n <= 1 return 1, otherwise return n * factorial(n - 1). In main print MathUtils.factorial(5) with print.
Starter code
// Define the MathUtils class, add the factorial method
void main() {
// print the result of factorial(5)
}Sample solution
class MathUtils {
static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
}
void main() {
print(MathUtils.factorial(5));
}Expected output
120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The group block
group('MathUtils', ____ { test('toplama', () {}); });
group('MathUtils', () { test('toplama', () {}); });
Explanation: the second parameter of group is a function: ().
2 What does group do?
- Throws an error
- Sets up a loop
- Groups related tests Correct answer
- Opens a file
Explanation: group gathers related tests together.
3 group parts
| Term | Meaning |
|---|---|
group('Math', () {}) |
Outer group |
group('factorial', () {}) |
Inner group |
test('zero', () {}) |
Test |