31

假设我在 Flutter 中使用WidgetTester. 有一个按钮,通过 执行导航Navigator。我想测试该按钮的行为。

小部件/屏幕

class MyScreen extends StatefulWidget {

  MyScreen({Key key}) : super(key: key);

  @override
  _MyScreenState createState() => _MyScreenScreenState();
}

class _MyScreenState extends State<MyScreen> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: RaisedButton(
                onPressed: () {
                    Navigator.of(context).pushNamed("/nextscreen");
                },
                child: Text(Strings.traktTvUrl)
            )
        )
    );
  }

}

测试

void main() {

  testWidgets('Button is present and triggers navigation after tapped',
      (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(home: MyScreen()));
    expect(find.byType(RaisedButton), findsOneWidget);
    await tester.tap(find.byType(RaisedButton));
    //how to test navigator?    
  });
}

我有一个正确的方法来检查,导航器被调用了吗?或者有没有办法模拟和替换导航器?

请注意,上面的代码实际上会因异常而失败,因为'/nextscreen'应用程序中没有声明命名路由。这很容易解决,您无需指出。

我主要关心的是如何在 Flutter 中正确处理这个测试场景。

4

4 回答 4

82

虽然 Danny 所说的是正确且有效的,但您也可以创建一个模拟的 NavigatorObserver 以避免任何额外的样板:

import 'package:mockito/mockito.dart';

class MockNavigatorObserver extends Mock implements NavigatorObserver {}

这将转化为您的测试用例,如下所示:

void main() {
  testWidgets('Button is present and triggers navigation after tapped',
      (WidgetTester tester) async {
    final mockObserver = MockNavigatorObserver();
    await tester.pumpWidget(
      MaterialApp(
        home: MyScreen(),
        navigatorObservers: [mockObserver],
      ),
    );

    expect(find.byType(RaisedButton), findsOneWidget);
    await tester.tap(find.byType(RaisedButton));
    await tester.pumpAndSettle();

    /// Verify that a push event happened
    verify(mockObserver.didPush(any, any));

    /// You'd also want to be sure that your page is now
    /// present in the screen.
    expect(find.byType(DetailsPage), findsOneWidget);
  });
}

我在我的博客上写了一篇关于这个的深入文章,你可以在这里找到

于 2018-08-23T10:01:47.797 回答
9

颤振 repo 的导航器测试中,他们使用NavigatorObserver类来观察导航:

class TestObserver extends NavigatorObserver {
  OnObservation onPushed;
  OnObservation onPopped;
  OnObservation onRemoved;
  OnObservation onReplaced;

  @override
  void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
    if (onPushed != null) {
      onPushed(route, previousRoute);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
    if (onPopped != null) {
      onPopped(route, previousRoute);
    }
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
    if (onRemoved != null)
      onRemoved(route, previousRoute);
  }

  @override
  void didReplace({ Route<dynamic> oldRoute, Route<dynamic> newRoute }) {
    if (onReplaced != null)
      onReplaced(newRoute, oldRoute);
  }
}

这看起来应该做你想做的事,但是它可能只能从顶层(MaterialApp)工作,我不确定你是否可以将它提供给一个小部件。

于 2018-06-05T20:59:31.470 回答
1

比方说,以下解决方案是一种通用方法,并不特定于 Flutter。

导航可以从屏幕或小部件中抽象出来。测试可以模拟和注入这个抽象。这种方法应该足以测试这种行为。

有几种方法可以实现这一目标。我将展示其中的一个,以便做出回应。也许可以稍微简化一下,或者让它更“Darty”。

导航抽象

class AppNavigatorFactory {
  AppNavigator get(BuildContext context) =>
      AppNavigator._forNavigator(Navigator.of(context));
}

class TestAppNavigatorFactory extends AppNavigatorFactory {
  final AppNavigator mockAppNavigator;

  TestAppNavigatorFactory(this.mockAppNavigator);

  @override
  AppNavigator get(BuildContext context) => mockAppNavigator;
}

class AppNavigator {
  NavigatorState _flutterNavigator;
  AppNavigator._forNavigator(this._flutterNavigator);

  void showNextscreen() {
    _flutterNavigator.pushNamed('/nextscreen');
  }
}

注入小部件

class MyScreen extends StatefulWidget {
  final _appNavigatorFactory;
  MyScreen(this._appNavigatorFactory, {Key key}) : super(key: key);

  @override
  _MyScreenState createState() => _MyScreenState(_appNavigatorFactory);
}

class _MyScreenState extends State<MyScreen> {
  final _appNavigatorFactory;

  _MyScreenState(this._appNavigatorFactory);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
            child: RaisedButton(
                onPressed: () {
                    _appNavigatorFactory.get(context).showNextscreen();
                },
                child: Text(Strings.traktTvUrl)
            )
        )
    );
  }

}

测试示例(使用Mockito 进行 Dart

class MockAppNavigator extends Mock implements AppNavigator {}

void main() {
  final appNavigator = MockAppNavigator();

  setUp(() {
    reset(appNavigator);
  });


  testWidgets('Button is present and triggers navigation after tapped',
      (WidgetTester tester) async {

    await tester.pumpWidget(MaterialApp(home: MyScreen(TestAppNavigatorFactory())));

    expect(find.byType(RaisedButton), findsOneWidget);
    await tester.tap(find.byType(RaisedButton));

    verify(appNavigator.showNextscreen());
  });
}
于 2018-06-06T11:15:44.873 回答
0

受其他帖子的启发,这是我 2022 年基于 null-safe Mockito 的方法。想象一下,我有这个要单元测试的辅助方法:

navigateToNumber(int number, BuildContext context) {
  Navigator.of(context).pushNamed(
      number.isEven ? '/even' : '/odd'
  );
}

可以这样测试:

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:mockito/annotations.dart';
import 'package:my_app/number_route_helper.dart';

import 'number_route_helper_test.mocks.dart';


@GenerateMocks([], 
  customMocks: [
    MockSpec<NavigatorObserver>(returnNullOnMissingStub: true)
  ])
void main() {
  group('NumberRouteHelper', () {
    testWidgets('navigateToNumber', (WidgetTester tester) async {
      final mockObserver = MockNavigatorObserver();

      // "Fake" routes used to verify the right route was pushed
      final evenRoute = MaterialPageRoute(builder: (_) => Container());
      final oddRoute = MaterialPageRoute(builder: (_) => Container());
      await tester.pumpWidget(
        MaterialApp(
          home: Container(),
          navigatorObservers: [mockObserver],
          onGenerateRoute: (RouteSettings settings) {
            switch (settings.name) {
            case '/even':
              return evenRoute;
            case '/odd':
              return oddRoute;
            }
          }
        ),
      );

      final BuildContext context = tester.element(find.byType(Container));

      /// Verify that a push to evenRoute happened 
      navigateToNumber(2, context);
      await tester.pumpAndSettle();
      verify(mockObserver.didPush(evenRoute, any));

      /// Verify that a push to oddRoute happened
      navigateToNumber(3, context);
      await tester.pumpAndSettle();
      verify(mockObserver.didPush(oddRoute, any));
    });
  });
}

请记住,您需要安装 Mockito,如下所述:https ://pub.dev/packages/mockito

于 2022-03-02T22:47:26.790 回答