–dart-define-from-file 在 Flutter 测试中的使用方法

huangapple go评论73阅读模式
英文:

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')
    );
  });
}

huangapple
  • 本文由 发表于 2023年6月13日 05:56:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定