CodeBlanks Logo Icon CodeBlanks

setUp and tearDown

Learn fixtures with setUp and tearDown.

setUp and tearDown

setUp(() { ... }) runs before each test, tearDown(() { ... }) runs after each test. This prepares a clean environment (fixture) for each test.

For example a Counter instance created in setUp lets every test start fresh. tearDown closes temporary files or connections.

These methods can be used inside a group; they then run only for that group's tests.

The fixture concept

A fixture is the environment a test runs in. In setUp you create an object and place it in a variable shared by tests. Each test receives it fresh.

For example late Counter c; setUp(() { c = Counter(); }); produces a new Counter for each test. Tests no longer affect each other.

tearDown cleans up at the end; it deletes temp files or closes connections.

Practice The Counter class

Define a Counter class with an int value = 0 field and a void increment() => value++ method. In main create a Counter, call increment() three times and print value with print.

Starter code

main.dart
// Define the Counter class (value, increment)

void main() {
  // create a Counter, call increment three times, print value
}

Sample solution

main.dart
class Counter {
  int value = 0;
  void increment() => value++;
}

void main() {
  var c = Counter();
  c.increment();
  c.increment();
  c.increment();
  print(c.value);
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does setUp run?

  • Once after all tests
  • Once at program start
  • Only on error
  • Before each test Correct answer

Explanation: setUp runs before each test.

2 The setUp block

Question
____(() {
  counter = Counter();
});
Answer
setUp(() {
  counter = Counter();
});

Explanation: setUp runs code before each test.

3 Fixture parts

Term Meaning
setUp Before test
tearDown After test
Counter() Fixture object
value Tested field

All lessons in Intermediate