英文:
How to use --dart-define-from-file in Flutter test
问题
这不是与如何在Flutter测试中使用--dart-define相同的问题。
使用Flutter 3.7版本,在运行时使用命令flutter run --dart-define-from-file=config.json
加载配置/环境变量到我的Flutter应用程序。为了进行测试,我应该如何确保在运行时加载测试配置文件?
英文:
This is NOT the same question as How to use --dart-define in Flutter test
Using the Flutter 3.7 release, I am loading config/env variables to my Flutter app at runtime using the command flutter run --dart-define-from-file=config.json
. For testing, how would I make sure a test config file is loading at runtime?
答案1
得分: 1
你可以创建一个新的单独配置文件(例如 "test_config.json"),其中包含要在测试期间加载的测试环境变量。
flutter test --dart-define-from-file=test_config.json
确保在你的应用中加载正确的配置文件。假设你正在使用 flutter_config
:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterConfig.loadEnvVariables();
runApp(MyApp());
}
这确保了测试配置文件在测试期间在运行时加载,允许使用所需的环境变量或配置进行测试。
此外,你可以在 flutter_config
包中使用 loadValueForTesting
来加载模拟变量:
void main() {
FlutterConfig.loadValueForTesting({'BASE_URL': 'https://www.mockurl.com'});
test('mock http client test', () {
final client = HttpClient(
baseUrl: FlutterConfig.get('BASE_URL')
);
});
}
英文:
You could create a new separate configuration file ("test_config.json" for example) that contains the test environment variables to be loaded during testing.
flutter test --dart-define-from-file=test_config.json
Make sure to load the proper configuration file in your app. Assuming that you are using flutter_config
:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterConfig.loadEnvVariables();
runApp(MyApp());
}
It ensures that the test configuration file is loaded at runtime during testing, allowing testing with the desired environment variables or configurations.
Additionally, you could use the loadValueForTesting
in the flutter_config
package to load mock variables:
void main() {
FlutterConfig.loadValueForTesting({'BASE_URL': 'https://www.mockurl.com'});
test('mock http client test', () {
final client = HttpClient(
baseUrl: FlutterConfig.get('BASE_URL')
);
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论