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.
-
2Does this answer your question? [Check if App is running in a Testing Environment](https://stackoverflow.com/questions/58407382/check-if-app-is-running-in-a-testing-environment) – Jannie Theunissen Feb 05 '21 at 14:05
2 Answers
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.

- 8,204
- 34
- 45
-
4
-
2I can't find an equivalent for Flutter web (since `dart:io` isn't available). Anyone know how to accomplish this in Flutter web? – Noland Mar 31 '22 at 16:37
-
@Noland you can write `if (kIsWeb == false && Platform.environment.containsKey('FLUTTER_TEST'))` and cover `flutter web` . – Esmaeil Ahmadipour Mar 22 '23 at 21:32
-
The accepted answer is right but if you want to check for a testing environment without breaking your web code, you can use the universal_io package.
Platform.environment.containsKey('FLUTTER_TEST')
On the web, Platform.environment will return an empty map instead of crashing your app.

- 11,488
- 3
- 53
- 61