Dart Flutter

Flutter automation testing-Flutter Driver

Flutter is a new technology for mobile development which has a lot of potential. More and more developers are starting to use Flutter for app development. And the community is still growing. Sometimes it is difficult for developers to find answers to their Flutter related questions. In this article, we will talk about Automated Testing of Flutter Apps, I will try to understand you in a very easy way with all those examples here, the video of this article is also available on YouTube. Testing is one of the most important steps in mobile app development whenever we create an app. Can’t build a high-quality app without testing it. The testing process requires precise planning and execution, but is also the most time-consuming part of development. The Flutter framework provides comprehensive support for automated testing of Flutter mobile applications. So let’s see step by step flutter automation testing.

These are some simple steps:-

1.Create an app to test:-

In this step you should have an app Either you can use the previous app you have or you can create a new one with flutter create command. this is a counter app which is allow to user tap the button to increase a counter .

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Center(

        child: Column(

          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              key: ValueKey('counter'),
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

There are some widgets here, on which you will see that you will find that.

 1. key: ValueKey('counter')
 2. tooltip: 'Increment',

What Is Key :-

The main limitation can be found on basically every widget manufacturer, yet their use is less common. The keys preserve position when widgets move around in your widget tree. It can be unique to any one widget.

What is Tooltip:-

A tooltip is a material design class in Flutter that provides text labels to explain the functionality .When a widget is equipped with tooltip, if user long presses the widget or some appropriate action on the widget, tooltip appears as a floating label.

2. flutter_driver dependency

In order to use the flutter_driver package to write integration tests, you must add the flutter_driver dependency to the dev_dependencies section of the pubspec.yaml file in the app root.

dev_dependencies:
  flutter_driver:
    sdk: flutter
  test: any

Full code

name: test_automation
description: A new Flutter project.


publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter



  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_driver:
    sdk: flutter
  test: any


flutter:

  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #

3. Next Create a first Test File

You need to create a folder in the root for test app name would be test _driver.

After that create two files inside this folder
One would be app.dart and the other would be app_test.dart

Look Like this :

Here you can create any file or folder inside test_driver on the basis of your test case.

app.dart

This will enable the Flutter driver and run the main function with it in the test case.

import 'package:flutter_driver/driver_extension.dart';
import 'package:test_automation/main.dart' as app;

void main() {
  // This line enables the extension.
  enableFlutterDriverExtension();

  // Call the `main()` function of the app, or call `runApp` with
  // any widget you are interested in testing.
  app.main();
}

Write the first test case

app_test.dart

// Imports the Flutter Driver API.
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';

void main() {
  group('Counter App', () {
    final counterTextFinder = find.byValueKey('counter');
    final buttonFinder = find.byTooltip('Increment');

    late FlutterDriver driver;

    // Connect to the Flutter driver before running any tests.
    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    // Close the connection to the driver after the tests have completed.
    tearDownAll(() async {
      driver.close();
    });

    test('starts at 0', () async {
      // Use the `driver.getText` method to verify the counter starts at 0.
      expect(await driver.getText(counterTextFinder), "0");
    });

    test('increments the counter', () async {
      // First, tap the button.
      await driver.tap(buttonFinder);

      // Then, verify the counter text is incremented by 1.
      expect(await driver.getText(counterTextFinder), "1");
    });

    test('increments the counter during animation', () async {
      await driver.runUnsynchronized(() async {
        // First, tap the button.
        await driver.tap(buttonFinder);

        // Then, verify the counter text is incremented by 1.
        expect(await driver.getText(counterTextFinder), "1");
      });
    });
  });
}

Now the app can see here that we are identifying the widget in the test case based on what I created in the beginning and a tooltip.Here both the names should be there.

    final counterTextFinder = find.byValueKey('counter');
    final buttonFinder = find.byTooltip('Increment');

Run the tests

Now that we’ve built an instrumentation app and a test suite, run the tests. To run the platform you are testing against, you have to run the following code in your terminal.

flutter drive --target=test_driver/app.dart

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *