首页 > 解决方案 > 如何使用 FlutterDriver 在 Flutter App 中测试原生 Android 方法?

问题描述

我的 Flutter 应用使用原生 Android 库。也就是说,它使用MethodChannel.

现在,我想测试通过MethodChannel. 由于MethodChannel需要调用 Java 进程,因此测试应该是集成测试,而不是单元测试。

如何在我的应用程序的集成测试中运行任何方法?

这是我的测试代码。

// app.dart
void main() {
  enableFlutterDriverExtension();
  app.main();
}
// app_test.dart
void main() {

  FlutterDriver driver;
  group("MyTests", () {
    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

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

    test("Test1", () async {
      var result1 = await CallNativeMethodWithMethodChannel.method1(value: -1);
      expect(false, result1);
      var result2 = await CallNativeMethodWithMethodChannel.method1(value: 0);
      expect(false, result2);
      var result3 = await CallNativeMethodWithMethodChannel.method1(value: 1);
      expect(true, result3);
    });

  });
}

执行此测试代码时,result1、result2 和 result3 将始终为 null。这意味着该方法不在应用程序上执行。

如何在我的应用程序上执行 method1?

(当然,我知道如果我在应用程序屏幕上准备一个按钮来运行测试并从测试代码中点击它是可以测试的,但实际上我们有100多个项目要测试,这并不实用准备 100 多个按钮。)

注意出于某种原因,我需要测试本机方法调用的结果。换句话说,模拟原生方法的执行结果是不合适的。另外,我想测试 Dart 代码和本机方法的组合,所以我不是“仅”测试本机方法。

标签: androidflutterdartflutter-test

解决方案


推荐阅读