Flutter Testing

Flutter - Introduction to Dart Programming

Flutter Testing

Testing is a crucial part of Flutter app development, ensuring that your app functions correctly, performs well, and remains bug-free as you update it. Flutter provides three types of testing:

  1. Unit Testing – Tests individual functions, methods, or classes.
  2. Widget Testing – Tests UI components and interactions.
  3. Integration Testing – Tests the complete app, including interactions with backend services.

1. Unit Testing

Unit tests verify the correctness of a single function, class, or method.

Steps to Write a Unit Test:
  • Add the flutter_test package to pubspec.yaml (Flutter includes this by default).
  • Create a test folder in the root directory.
  • Write test cases using test() from the test package.

Example: Testing a Math Function

Create a file test/math_test.dart:


  import 'package:flutter_test/flutter_test.dart';

  // Function to be tested
  int add(int a, int b) {
    return a + b;
  }

  void main() {
    test('Addition function test', () {
      expect(add(2, 3), 5);
      expect(add(-1, 1), 0);
    });
  }

Run the Test

Run the test in the terminal:

flutter test test/math_test.dart


2. Widget Testing

Widget tests (or UI tests) ensure that UI components work as expected.

Example: Testing a Button Click

Create test/widget_test.dart:


  import 'package:flutter/material.dart';
  import 'package:flutter_test/flutter_test.dart';

  void main() {
    testWidgets('Button press changes text', (WidgetTester tester) async {
      await tester.pumpWidget(MyApp());

      // Verify initial text
      expect(find.text('Press Me!'), findsOneWidget);
      expect(find.text('Pressed!'), findsNothing);

      // Tap the button
      await tester.tap(find.byType(ElevatedButton));
      await tester.pump();

      // Verify the text changed
      expect(find.text('Pressed!'), findsOneWidget);
    });
  }

  class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          body: Center(
            child: MyWidget(),
          ),
        ),
      );
    }
  }

  class MyWidget extends StatefulWidget {
    @override
    _MyWidgetState createState() => _MyWidgetState();
  }

  class _MyWidgetState extends State<MyWidget> {
    String text = 'Press Me!';

    @override
    Widget build(BuildContext context) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(text),
          ElevatedButton(
            onPressed: () {
              setState(() {
                text = 'Pressed!';
              });
            },
            child: Text('Press'),
          ),
        ],
      );
    }
  }

Run Widget Test

flutter test test/widget_test.dart


3. Integration Testing

Integration tests check the complete app, simulating real user interactions.

Steps for Integration Testing:

Add integration_test dependency to pubspec.yaml:


  dev_dependencies:
    integration_test:
      sdk: flutter
    flutter_test:
      sdk: flutter

Create a test_driver folder and inside it, create integration_test.dart:


  // Import necessary packages
  import 'package:flutter_test/flutter_test.dart';
  import 'package:integration_test/integration_test.dart';
  import 'package:my_app/main.dart'; // Import your main app

  void main() {
    IntegrationTestWidgetsFlutterBinding.ensureInitialized();

    // Define the test
    testWidgets('Check if button works', (WidgetTester tester) async {
      // Load the app
      await tester.pumpWidget(MyApp());

      // Verify the initial text
      expect(find.text('Press Me!'), findsOneWidget);

      // Simulate button tap
      await tester.tap(find.byType(ElevatedButton));
      await tester.pump();

      // Verify the text changed
      expect(find.text('Pressed!'), findsOneWidget);
    });
  }

Run Integration Test

flutter drive --driver=test_driver/integration_test.dart


  • Unit Tests: Check small parts of the code (e.g., functions).
  • Widget Tests: Validate UI components (e.g., buttons, text).
  • Integration Tests:Test the entire app workflow.
  • أحدث أقدم