Back to results for “Dependency Injection in Flutter (GetIt & Service Locator)”
Flutter › Unit Testing in Flutter

How do setUp and tearDown let you properly share common test setup and cleanup logic consistently across several genuinely separate related tests within the exact same group?

Intermediate

Answer

setUp is genuinely called automatically before every single individual test genuinely runs within its own enclosing group, letting you properly perform common shared setup work, such as creating a fresh new instance of the specific class actually genuinely being tested, ensuring every single test genuinely starts from exactly the same clean, consistent known starting state, while tearDown is genuinely called automatically after every single test genuinely completes, letting you properly clean up any resources that particular test may have actually used, such as properly closing a test database connection.
late Calculator calculator;

setUp(() {
  calculator = Calculator();
});

test('adds two numbers', () {
  expect(calculator.add(2, 3), 5);
});
Real-world example A test suite for a Calculator class uses setUp to properly create a genuinely fresh new Calculator instance before each individual separate test, correctly ensuring no leftover state from one particular test could ever accidentally affect a genuinely separate subsequent test.

Common follow-ups: What genuinely happens if setUp itself genuinely throws an exception partway through?;What is the specific practical difference between setUp and the considerably less commonly used setUpAll?