joh*_*zli 5 google-maps mocking mockito flutter flutter-test
我最近开始接触 flutter,但就在我准备编写一些小部件测试时,我注意到我不太确定如何模拟 Google Maps Flutter 包。
我见过的许多例子包括使用库“mockito”来模拟类,但这假设谷歌地图小部件将被注入到要测试的小部件中。不幸的是,根据他们给定的文档和启动指南,这似乎不太可能:
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; });
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,GoogleMaps无法传入小部件,因为onMapCreated它是必需的函数,并且该函数依赖于私有类方法(授予父小部件访问权限GoogleMapsController)。mockito 模拟函数的许多其他示例没有这种回调函数来设置状态。
我似乎没有看到任何其他包可以有效地模拟 GoogleMaps 小部件,所以我真的没有任何可以遵循的示例。理想情况下,我期望的是 node.s 中的 proxyquire 或 sinon 之类的某种行为(您不需要将模拟库传递到 function.constructors 中),但看起来模拟类需要传递到测试的小部件。
关于如何模拟这个库进行测试还有其他想法吗?还是我应该只测试实际功能?
我设法通过模拟 GoogleMaps 使用的频道来模拟它:
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;
});
}
Run Code Online (Sandbox Code Playgroud)
我从这个 webview 插件测试(这是一个像 GoogleMaps 小部件一样的 PlatformView)以及这个 GoogleMaps 插件测试中得到了灵感
| 归档时间: |
|
| 查看次数: |
489 次 |
| 最近记录: |