Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Flutter Testing

23. Flutter Testing(Unit, Widget, Integration)

Testing is a critical part of Flutter development to ensure your app functions as expected and remains bug-free. Flutter offers different types of testing: unit testing, widget testing, and integration testing. In this tutorial, we'll cover each type with examples.

1. Unit Testing

Unit testing focuses on testing individual functions or units of your code in isolation.

Step 1: Set Up Your Project

Create a Flutter project or use an existing one.

Step 2: Write a Function to Test

Create a Dart function that you want to test. For example, let's write a simple function that adds two numbers:
int add(int a, int b) {
  return a + b;
}
 

Step 3: Write Unit Tests

Create a unit test file (e.g., 'add_test.dart') in your project's 'test' directory.
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app_name/main.dart'; // Replace with your app's main.dart

void main() {
  test('Adding two numbers', () {
    expect(add(2, 3), 5); // Replace with your function and expected result
  });
}
 

Step 4: Run Unit Tests

Run your unit tests using the following command:
flutter test
 

Flutter will execute the tests, and you'll see the results in your terminal.

2. Widget Testing

Widget testing is used to test individual Flutter widgets in isolation.

Step 1: Set Up Your Project

Create a Flutter project or use an existing one.

Step 2: Write a Widget to Test

Create a Flutter widget that you want to test. For example, let's create a simple widget that displays a counter:
import 'package:flutter/material.dart';

class CounterWidget extends StatefulWidget {
  @override
  _CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State {
  int count = 0;

  void increment() {
    setState(() {
      count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Count: $count'),
        ElevatedButton(
          onPressed: increment,
          child: Text('Increment'),
        ),
      ],
    );
  }
}
 

Step 3: Write Widget Tests

Create a widget test file (e.g., 'counter_widget_test.dart') in your project's 'test' directory.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app_name/main.dart'; // Replace with your app's main.dart
import 'package:your_app_name/counter_widget.dart'; // Replace with your widget

void main() {
  testWidgets('CounterWidget increments counter', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      home: CounterWidget(),
    ));

    expect(find.text('Count: 0'), findsOneWidget);
    expect(find.text('Count: 1'), findsNothing);

    await tester.tap(find.byType(ElevatedButton));
    await tester.pump();

    expect(find.text('Count: 0'), findsNothing);
    expect(find.text('Count: 1'), findsOneWidget);
  });
}
 

Step 4: Run Widget Tests

Run your widget tests using the following command:
flutter test
 

Flutter will execute the widget tests, and you'll see the results in your terminal.

3. Integration Testing

Integration testing involves testing how different parts of your app work together.

Step 1: Set Up Your Project

Create a Flutter project or use an existing one.

Step 2: Write Integration Tests

Create an integration test file (e.g., 'integration_test.dart') in your project's 'test' directory.
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';

void main() {
  group('Integration Tests', () {
    FlutterDriver driver;

    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        driver.close();
      }
    });

    test('Increment counter', () async {
      // Find the button and tap it
      final incrementButton = find.byValueKey('increment_button');
      await driver.tap(incrementButton);

      // Find the text widget and verify the count
      final counterText = find.byValueKey('counter_text');
      expect(await driver.getText(counterText), 'Count: 1');
    });
  });
}
 

Step 3: Add Integration Test Keys

In your app code, add keys to the widgets you want to interact with in your integration tests. For example, add keys to the button and text widget in your 'counterWidge':
ElevatedButton(
  key: Key('increment_button'), // Add a key to the button
  onPressed: increment,
  child: Text('Increment'),
),
Text(
  'Count: $count',
  key: Key('counter_text'), // Add a key to the text widget
),
 

Step 4: Run Integration Tests

Run your integration tests using the following command:
flutter drive --target=test_driver/app.dart
 

This command will launch your app in a test environment, and Flutter Driver will execute the integration tests.

Conclusion:

Testing is an essential part of Flutter development to ensure your app is reliable and works as expected. Unit, widget, and integration tests help you catch and fix issues early in the development process.