[英]How to test a method that uses package_info in Flutter?
I am writing a Flutter plugin that checks the Play Store or App Store to see if the app needs to be updated.我正在编写一个 Flutter 插件,用于检查 Play Store 或 App Store 以查看应用程序是否需要更新。 I'm using the
package_info
package to determine the version of the app that the user has.我正在使用
package_info
包来确定用户拥有的应用程序的版本。 My code looks like this:我的代码如下所示:
getVersionStatus() {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
localVersion = packageInfo.version;
...
}
I want to test this method, but if it run it as a unit test the fromPlatform
call just hangs and times out the test.我想测试这个方法,但如果它作为单元测试运行,
fromPlatform
调用只会挂起并超时测试。 Is there a more elegant way to solve this than passing in a testing
boolean?有没有比传入
testing
布尔值更优雅的方法来解决这个问题? Ie: IE:
if (testing) {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
localVersion = packageInfo.version;
} else {
localVersion = '0.0.0'
}
Should the package_info
package provide a way to catch errors? package_info
包是否应该提供一种捕获错误的方法? Is there a way to tell if the method is being run by a test?有没有办法判断该方法是否正在通过测试运行?
Like Günter said, you can mock PackageInfo by installing a mock method handler in the MethodChannel for the plugin:正如 Günter 所说,您可以通过在插件的 MethodChannel 中安装模拟方法处理程序来模拟PackageInfo :
void packageInfoMock() {
const MethodChannel('plugins.flutter.io/package_info').setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{
'appName': 'ABC', // <--- set initial values here
'packageName': 'A.B.C', // <--- set initial values here
'version': '1.0.0', // <--- set initial values here
'buildNumber': '' // <--- set initial values here
};
}
return null;
});
}
PackageInfo.setMockInitialValues(appName: "abc", packageName: "com.example.example", version: "1.0", buildNumber: "2", buildSignature: "buildSignature");
I delegated the PackageInfo access to a repository object.我委托 PackageInfo 访问存储库对象。 This repo then is easy to mock.
这个 repo 很容易模拟。 This also works for package_info_plus.
这也适用于 package_info_plus。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.