Flutter行为驱动开发插件flutter_gherkin的使用

发布于 1周前 作者 yuanlaile 来自 Flutter

Flutter行为驱动开发插件flutter_gherkin的使用

简介

flutter_gherkin 是一个功能齐全的Gherkin解析器和测试运行器,适用于Flutter和Dart 2。它遵循Cucumber的各种形式,提供了一种行为驱动开发(BDD)的方法来编写和执行测试。

安装与配置

添加依赖

pubspec.yaml 文件中添加 flutter_gherkin 依赖:

dev_dependencies:
  flutter_gherkin: ^x.x.x # 替换为最新版本号

创建可测试应用

创建一个名为 test_driver/app.dart 的文件,并启用Flutter Driver扩展:

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

void main() {
  enableFlutterDriverExtension();
  app.main();
}

编写Feature文件

test_driver/features 目录下创建 .feature 文件,例如 counter.feature

Feature: Counter
  The counter should be incremented when the button is pressed.

  Scenario: Counter increases when the button is pressed
    Given I expect the "counter" to be "0"
    When I tap the "increment" button 10 times
    Then I expect the "counter" to be "10"

实现步骤定义

创建一个自定义步骤定义类,例如 tap_button_n_times_step.dart

import 'package:flutter_driver/flutter_driver.dart';
import 'package:flutter_gherkin/flutter_gherkin.dart';
import 'package:gherkin/gherkin.dart';

StepDefinitionGeneric TapButtonNTimesStep() {
  return when2<String, int, FlutterWorld>(
    'I tap the {string} button {int} times',
    (key, count, context) async {
      final locator = find.byValueKey(key);
      for (var i = 0; i < count; i++) {
        await FlutterDriverUtils.tap(context.world.driver, locator);
      }
    },
  );
}

配置测试

创建 test_driver/app_test.dart 文件并配置测试:

import 'dart:async';
import 'package:flutter_gherkin/flutter_gherkin.dart';
import 'package:gherkin/gherkin.dart';
import 'steps/tap_button_n_times_step.dart';

Future<void> main() {
  final config = FlutterTestConfiguration()
    ..features = [RegExp(r'test_driver/features/*.feature')]
    ..reporters = [
      ProgressReporter(),
      TestRunSummaryReporter(),
      JsonReporter(path: './report.json')
    ]
    ..stepDefinitions = [TapButtonNTimesStep()]
    ..restartAppBetweenScenarios = true
    ..targetAppPath = "test_driver/app.dart";

  return GherkinRunner().execute(config);
}

运行测试

在命令行中运行以下命令:

dart test_driver/app_test.dart

示例代码

以下是完整的示例代码,包括一个简单的计数器应用及其对应的测试:

主应用代码 (lib/main.dart)

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Counter App',
      home: MyHomePage('Counter App Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage(this.title) : super();

  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>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              key: const Key('counter'),
              style: Theme.of(context).textTheme.headline4,
            ),
            FloatingActionButton(
              key: const Key('increment'),
              onPressed: _incrementCounter,
              tooltip: 'Increment',
              child: const Icon(Icons.add),
            ),
          ],
        ),
      ),
    );
  }
}

测试代码 (test_driver/app_test.dart)

import 'dart:async';
import 'package:flutter_gherkin/flutter_gherkin.dart';
import 'package:gherkin/gherkin.dart';
import 'steps/tap_button_n_times_step.dart';

Future<void> main() {
  final config = FlutterTestConfiguration()
    ..features = [RegExp(r'test_driver/features/*.feature')]
    ..reporters = [
      ProgressReporter(),
      TestRunSummaryReporter(),
      JsonReporter(path: './report.json')
    ]
    ..stepDefinitions = [TapButtonNTimesStep()]
    ..restartAppBetweenScenarios = true
    ..targetAppPath = "test_driver/app.dart";

  return GherkinRunner().execute(config);
}

Feature文件 (test_driver/features/counter.feature)

Feature: Counter
  The counter should be incremented when the button is pressed.

  Scenario: Counter increases when the button is pressed
    Given I expect the "counter" to be "0"
    When I tap the "increment" button 10 times
    Then I expect the "counter" to be "10"

步骤定义 (steps/tap_button_n_times_step.dart)

import 'package:flutter_driver/flutter_driver.dart';
import 'package:flutter_gherkin/flutter_gherkin.dart';
import 'package:gherkin/gherkin.dart';

StepDefinitionGeneric TapButtonNTimesStep() {
  return when2<String, int, FlutterWorld>(
    'I tap the {string} button {int} times',
    (key, count, context) async {
      final locator = find.byValueKey(key);
      for (var i = 0; i < count; i++) {
        await FlutterDriverUtils.tap(context.world.driver, locator);
      }
    },
  );
}

通过以上步骤,您可以开始使用 flutter_gherkin 进行行为驱动开发,并确保您的Flutter应用按预期工作。


更多关于Flutter行为驱动开发插件flutter_gherkin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter行为驱动开发插件flutter_gherkin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter项目中实施行为驱动开发(BDD)时,flutter_gherkin 是一个强大的工具,它允许你使用 Gherkin 语法编写测试用例。以下是一个基本的示例,展示了如何在 Flutter 项目中设置和使用 flutter_gherkin

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加 flutter_gherkin 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_test:
    sdk: flutter
  flutter_gherkin: ^x.y.z  # 替换为最新版本号

然后运行 flutter pub get 来获取依赖。

2. 编写 Feature 文件

创建一个 .feature 文件,比如 example.feature,并使用 Gherkin 语法编写测试用例:

Feature: Example feature
  Scenario: User can see a welcome message
    Given I have started the app
    When I navigate to the welcome screen
    Then I should see the welcome message

3. 编写 Step 定义

创建一个 Dart 文件,比如 steps.dart,来定义步骤的实现:

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

void main() {
  FlutterGherkin.defineFeature({
    'I have started the app': (World world) async {
      await FlutterDriver.connectToServiceProtocol(world.parameters['flutter_test_url']);
    },
    'I navigate to the welcome screen': (World world) async {
      final driver = world.getDriver();
      await driver.tap(find.byValueKey('welcome_button_key'));
      await driver.waitFor(find.byValueKey('welcome_screen_key'));
    },
    'I should see the welcome message': (World world) async {
      final driver = world.getDriver();
      final welcomeText = await driver.findTextContaining(new RegExp(r'Welcome'));
      expect(welcomeText, isNotNull);
    }
  }, tags: ['@my_tag']);
}

4. 配置 Flutter Gherkin

创建一个 config.yaml 文件来配置 flutter_gherkin

flutter:
  sdk: "path_to_your_flutter_sdk"
  app:
    path: "path_to_your_flutter_app"
gherkin:
  features:
    - "path_to_your_features/example.feature"
  steps:
    - "path_to_your_steps/steps.dart"
  syntax_highlighting: true
  report:
    enabled: true
    directory: "path_to_your_report_directory"
  parameters:
    flutter_test_url: "http://127.0.0.1:YOUR_FLUTTER_DRIVER_PORT"

5. 运行测试

确保你的 Flutter 应用正在运行并且 Flutter Driver 端口是已知的(你可以在运行应用时通过命令行参数指定端口)。然后运行 flutter gherkin 命令:

flutter gherkin --config=config.yaml

总结

以上代码示例展示了如何在 Flutter 项目中设置和使用 flutter_gherkin 进行行为驱动开发。通过编写 .feature 文件和相应的步骤定义,你可以轻松地将 Gherkin 语法与 Flutter 测试框架结合使用,从而创建可读且可维护的测试用例。

回到顶部