如何模拟'google_maps_flutter'软件包进行颤动测试?

时间:2019-01-20 07:48:32

标签: google-maps mocking flutter mockito flutter-test

我最近开始陷入困境,但是正当我要编写一些小部件测试时,我注意到我不太确定如何模拟出Google Maps Flutter软件包。

我看到的许多示例都包括使用库“ mockito”来模拟类,但这假设Google Maps小部件将注入到要测试的小部件中。不幸的是,根据他们给定的文档和启动指南,这似乎不太可能:

class MapsDemo extends StatefulWidget {
  @override
  State createState() => MapsDemoState();
}

class MapsDemoState extends State<MapsDemo> {

  GoogleMapController mapController;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(15.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          Center(
            child: SizedBox(
              width: 300.0,
              height: 200.0,
              child: GoogleMap(
                onMapCreated: _onMapCreated,
              ),
            ),
          ),
          RaisedButton(
            child: const Text('Go to London'),
            onPressed: mapController == null ? null : () {
              mapController.animateCamera(CameraUpdate.newCameraPosition(
                const CameraPosition(
                  bearing: 270.0,
                  target: LatLng(51.5160895, -0.1294527),
                  tilt: 30.0,
                  zoom: 17.0,
                ),
              ));
            },
          ),
        ],
      ),
    );
  }

  void _onMapCreated(GoogleMapController controller) {
    setState(() { mapController = controller; });
  }
}

请注意,无法传递GoogleMaps小部件,因为onMapCreated是必需的函数,并且该函数依赖于私有类方法(允许父小部件访问GoogleMapsController)。很多其他不具有这种回调函数来设置状态的模拟嘲笑函数的示例。

似乎没有其他软件包可以有效地模拟GoogleMaps小部件,因此我实际上没有任何可遵循的示例。理想情况下,我期望的是某种行为,例如node.s中的proxyquire或sinon(您无需将模拟库传递到function.constructors中),但是看起来模拟类需要传递到经过测试的小部件。

关于如何模拟该库进行测试还有其他想法吗?还是应该只测试实际功能?

1 个答案:

答案 0 :(得分:0)

我设法通过模拟使用的渠道来模拟GoogleMap:

setUpAll(() async {
  SystemChannels.platform_views.setMockMethodCallHandler((MethodCall call) {
    switch (call.method) {
      case 'create':
        return Future<int>.sync(() => 1);
      default:
        return Future<void>.sync(() {});
    }
  });

  MethodChannel('plugins.flutter.io/google_maps_0', StandardMethodCodec())
    .setMockMethodCallHandler((MethodCall methodCall) async {
      return null;
    });
}

我从这个webview插件test(类似于GoogleMaps小部件的PlatformView)以及这个GoogleMaps插件test

中得到了启发。
相关问题