0
0
Fluttermobile~5 mins

Unit testing in Flutter

Choose your learning style9 modes available
Introduction

Unit testing helps check small parts of your app to make sure they work right. It finds mistakes early so your app is more reliable.

When you want to check if a function returns the correct result.
When you change code and want to make sure nothing else breaks.
When you build a feature and want to test its logic separately.
When you want to save time by catching bugs before running the full app.
Syntax
Flutter
import 'package:test/test.dart';

void main() {
  test('description of test', () {
    // code to test
    expect(actual, expected);
  });
}

The test function defines a single test case with a description.

The expect function checks if the actual value matches the expected value.

Examples
This test checks if 2 plus 3 equals 5.
Flutter
test('adding two numbers', () {
  var sum = 2 + 3;
  expect(sum, 5);
});
This test checks if the string contains the word 'world'.
Flutter
test('string contains substring', () {
  var text = 'hello world';
  expect(text.contains('world'), true);
});
Sample App

This program tests a simple multiply function with two cases: normal multiplication and multiplication by zero.

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

int multiply(int a, int b) {
  return a * b;
}

void main() {
  test('multiply two numbers', () {
    expect(multiply(4, 5), 20);
  });

  test('multiply by zero', () {
    expect(multiply(7, 0), 0);
  });
}
OutputSuccess
Important Notes

Write small, focused tests that check one thing at a time.

Run tests often to catch errors early.

Use clear descriptions so you know what each test checks.

Summary

Unit tests check small parts of your code to find bugs early.

Use test and expect to write tests in Flutter.

Run tests regularly to keep your app reliable.