Skip to content

Instantly share code, notes, and snippets.

@begomez
Created September 20, 2022 16:04
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save begomez/be4a6dac7508333ff32a5ada334b3b7e to your computer and use it in GitHub Desktop.
Flutter: testing a method channel
/*
import 'package:url_launcher/url_launcher.dart';
class AppStoreLauncherException implements Exception {
final String msg;
const AppStoreLauncherException(this.msg) : super();
}
class AppStoreLauncher {
const AppStoreLauncher() : super();
Future<void> launchWebStore({bool isAndroid = true}) async {
String url = 'https://apps.apple.com/...';
if (isAndroid) {
url = 'https://play.google.com/store/apps/details?id=...';
}
if (await canLaunch(url)) {
await launch(url);
} else {
throw AppStoreLauncherException('Could not launch $url');
}
}
}
*/
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:ssu_life/features/splash/domain/helper/app_store_launcher.dart';
void main() {
late List<MethodCall> fakeLog;
late MethodChannel mockChannel;
late AppStoreLauncher launcher;
void _mockChannelValues({bool canLaunch = true, bool launch = true}) {
TestDefaultBinaryMessengerBinding.instance!.defaultBinaryMessenger.setMockMethodCallHandler(mockChannel,
(MethodCall methodCall) async {
fakeLog.add(methodCall);
if (methodCall.method == "canLaunch") {
return canLaunch;
} else if (methodCall.method == "launch") {
return launch;
}
return false;
});
}
setUp(() {
fakeLog = <MethodCall>[];
mockChannel = const MethodChannel('plugins.flutter.io/url_launcher');
launcher = const AppStoreLauncher();
TestWidgetsFlutterBinding.ensureInitialized();
});
tearDown(() {
fakeLog = <MethodCall>[];
});
test('When launching android store both canLaunch and launch are invoked', () async {
_mockChannelValues(canLaunch: true, launch: true);
await launcher.launchWebStore(isAndroid: true);
expect(fakeLog.length, 2);
expect(
fakeLog.map((e) => e.method),
equals(<String>[
'canLaunch',
'launch',
]));
});
test('When launching ios store both canLaunch and launch are invoked', () async {
_mockChannelValues(canLaunch: true, launch: true);
await launcher.launchWebStore(isAndroid: false);
expect(fakeLog.length, 2);
expect(
fakeLog.map((e) => e.method),
equals(<String>[
'canLaunch',
'launch',
]));
});
test('When launching android only canLaunch invoked', () async {
_mockChannelValues(canLaunch: false, launch: true);
final actual = launcher.launchWebStore;
expect(() async => actual.call(isAndroid: true), throwsA(isA<AppStoreLauncherException>()));
expect(fakeLog.length, 1);
expect(
fakeLog.map((e) => e.method),
equals(<String>[
'canLaunch',
]));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment