2

In those questions:

The given solution is to use

Platform.environment.containsKey('FLUTTER_TEST')

but Platform comes from dart:io which is not supported on web. If I import it from universal_io, it returns false when I run the tests with

flutter test --platform chrome

How to get a similar method/variable in a web environment?

Valentin Vignal
  • 6,151
  • 2
  • 33
  • 73

2 Answers2

0

I was also looking for a solution but the line:

Platform.environment.containsKey('FLUTTER_TEST')

or the line:

Get.testMode

do not seem to work during integration testing, for example. So I just created a singleton class that holds a variable isTest set to false as default.

class TestController {
  static final _testController = TestController._internal();

  TestController._internal();

  factory TestController() {
    return _testController;
  }

  bool isTest = false;
}

And i change it to true at the start of the integration test:

void main() {
  enableFlutterDriverExtension();
  TestController().isTest = true;
  app.main();
}

Maybe is not that elegant as a solution, I know, but it works in my case at least. That way I can successfully inject the appropriate dependencies I need for test and production environments.

 void _setWindowAndInjectDependencies() {
    final isTest = TestController().isTest;
    DesktopWindow.setWindowSize(const Size(1060, 960));
    DesktopWindow.setMinWindowSize(const Size(1060, 960));
    _loadCommonDependencies();
    if (!isTest) {
      print("Not Test Mode");
      _loadMacDependencies();
    } else {
      _loadTestDependencies();
    }
  }

I hope this provides some help.

MatBuompy
  • 402
  • 5
  • 12
-1

Why do you want to detect if you're in a test?

You could always just create a top-level static in a library you control

bool runningInATest = false; and then set it to true in your test app?

Kevin Moore
  • 5,921
  • 2
  • 29
  • 43
  • During the tests, some services might want to mock some side effects like reading files/creating them/writing in the cache etc. Yes, I still could create this variable, but I would want it to be final, so devs cannot change it. This requires some work and if something is already done like `Platform.environment.containsKey('FLUTTER_TEST')`, it is better to not redo the work – Valentin Vignal Sep 16 '22 at 06:15