Reputation: 8240
When using Flutter, it is possible to define a variable
final isTest = Platform.environment.containsKey('FLUTTER_TEST');
which will be true
when using flutter test
and false
otherwise.
Is there an equivalent for when using dart test
? I tried to inspect Platform.environment
but didn't find anything specific to dart.
Upvotes: 0
Views: 336
Reputation: 90025
I don't think that there's any direct way to detect if your code is running via dart test
. However, you generally should avoid writing such code. Code that checks if it's being tested so that it can behave differently in a test guarantees that your test coverage will not execute the non-test code paths. Instead, your code should be parameterized (perhaps with a formal dependency injection framework) so that the tests can supply mocks or fakes to the code being tested.
If your goal is to generate additional diagnostic output during tests, then test coverage won't be a problem. However, in such a case you should be using something like package:logging
, unconditionally call logging functions, and have only your tests configure those logging functions to generate actual output.
But if you still really want to detect if your code is running via dart test
, then an indirect way could be to check Platform.script
to see if your code is being executed by the test runner:
bool isRunByDartTestRunner() => Platform.script.contains('/dart_test.');
However, do note that the above isn't foolproof:
/dart_test.
in its path.dart test
and not for tests wrapped by some other testing framework.And, of course, another option would be to simply have the code being tested provide some global bool
variable, and then make your tests explicitly set it.
(If https://github.com/dart-lang/sdk/issues/28160 ever gets addressed, then another option would be to have your tests explicitly set an environment variable themselves.)
Upvotes: 1