While calling a function from unit test in Flutter (Dart), how can I find if I am running unit test or real application? I want to pass different data if it's in unit test.
You can use the following to check if you're running a test.
Platform.environment.containsKey('FLUTTER_TEST')
Solution for web below
Note that the code above doesn't work on web as the Platform
class is part of dart:io
which is not available on web. An alternative solution that works for all platforms including web would be to use --dart-define
build environment variable. It is available from Flutter 1.17
Example of running tests with --dart-define
:
flutter drive --dart-define=testing_mode=true --target=test_driver/main.dart
In code you can check this environment variable with the following code:
const bool.fromEnvironment('testing_mode', defaultValue: false)
Not using const can lead to the variable not being read on mobile, see here.