Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if App is running in a Testing Environment

Tags:

flutter

dart

was just wondering if I can determine if my app currently runs in a Testing environment. Reason is that I am running automated screenshots and want to hide/modify parts of my App only when running that UI Test.

For example I'd like to skip registering for push notifications to avoid that iOS Popup at launch.

I'm searching for something like

if (kTestingMode) { ... } 

I know that we do have a driver that basically launches the app and then connects. Guess the App actually does not even know if it is running in Testmode or not. But maybe someone knows an answer.

Thanks!

like image 326
Robin Reiter Avatar asked Oct 16 '19 06:10

Robin Reiter


2 Answers

Some answers aim to detect if you are in debug mode. The question was about how to detect if you are in a test environment, not if you are in debug mode. In fact, when you run a test, you are in debug mode, but you can run an app in debug mode even without running a test.

In order to properly detect if you are running a test, you can check for the presence of the key FLUTTER_TEST in Platform.environment.

import 'dart:io' show Platform;

if (Platform.environment.containsKey('FLUTTER_TEST')) { ... } 
like image 128
Luca Venturini Avatar answered Sep 22 '22 17:09

Luca Venturini


Another solutions is 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.

like image 41
Katarina Sheremet Avatar answered Sep 22 '22 17:09

Katarina Sheremet