0
0
FlutterHow-ToBeginner · 4 min read

How to Use Unit Test in Flutter: Simple Guide

To use unit test in Flutter, add the test package to your project, write test functions using test(), and run them with flutter test. Unit tests check small parts of your code, like functions, to ensure they work correctly.
📐

Syntax

In Flutter, unit tests use the test package. You write tests inside test() functions, which take a description and a callback with your test code. Use expect() to check if values match what you expect.

  • test('description', () { ... }): Defines a test case.
  • expect(actual, matcher): Checks if actual value meets the matcher.
dart
import 'package:test/test.dart';

void main() {
  test('description of test', () {
    var result = 2 + 2;
    expect(result, 4);
  });
}
💻

Example

This example shows a simple function and a unit test that checks if it returns the correct sum.

dart
import 'package:test/test.dart';

int add(int a, int b) {
  return a + b;
}

void main() {
  test('add returns the sum of two numbers', () {
    expect(add(3, 4), 7);
    expect(add(-1, 1), 0);
  });
}
Output
+0: All tests passed! 00:00 +2: All tests passed!
⚠️

Common Pitfalls

Common mistakes include:

  • Not importing the test package.
  • Writing tests that depend on Flutter widgets instead of pure logic (use widget tests for UI).
  • Forgetting to run flutter test in the project root.
  • Using print() instead of expect() for checking results.
dart
import 'package:test/test.dart';

// Wrong: no expect, just print
void main() {
  test('wrong test', () {
    var result = 2 + 2;
    print(result); // This does not check anything
  });
}

// Right: use expect
void main() {
  test('correct test', () {
    var result = 2 + 2;
    expect(result, 4);
  });
}
📊

Quick Reference

CommandDescription
flutter testRun all unit tests in the project
test('desc', () { ... })Define a single test case
expect(actual, matcher)Check if actual value matches expected
setUp(() { ... })Run code before each test
tearDown(() { ... })Run code after each test

Key Takeaways

Add the 'test' package and write tests using 'test()' and 'expect()'.
Run tests with 'flutter test' from your project root folder.
Unit tests check small pieces of logic, not UI components.
Avoid using print statements; always use 'expect()' to verify results.
Use setUp and tearDown to prepare and clean up before/after tests.