How to find if we are running unit test in Dart (Flutter)
Asked Answered
P

3

28

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.

Platter answered 25/11, 2019 at 9:25 Comment(1)
Does this answer your question? Check if App is running in a Testing EnvironmentNectareous
C
76

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.

Chlodwig answered 25/11, 2019 at 9:40 Comment(4)
Platform is defined in dart:ioTeahan
I can't find an equivalent for Flutter web (since dart:io isn't available). Anyone know how to accomplish this in Flutter web?Winniewinnifred
@Winniewinnifred you can write if (kIsWeb == false && Platform.environment.containsKey('FLUTTER_TEST')) and cover flutter web .Eparch
This does not work for integration tests for me.Tetragon
P
1

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.

Phototaxis answered 7/9, 2022 at 18:18 Comment(0)
D
0

Mobile only:

import 'dart:io';

Web & Mobile:

import 'package:universal_io/io.dart';

Then in your function:

if(Platform.environment.containsKey('FLUTTER_TEST')) {
  //add your code here
}

Using the instance of Platform from dart:io will crash on web when you are not in test mode, so make sure to always use the universal_io/io's instance.

I tested it with universal_io: ^2.2.2 which is working perfectly on all platforms. It seems it wasn't working on older versions as @12806961 stated in his answer.

If you want to use dart:io for mobile and universal_io: ^2.2.2 for web, you can always have conditional import/export of a variable that you would create globally for the project.

Dethrone answered 27/6 at 8:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.