How to pass parameters into flutter integration_test?

Issue

I used flutter_driver before for integration tests and was able to insert parameters to the test via environment variables from the host, as the test was running from the host.

For another project I am now using the integration_test package.

The test is not running any longer on the host but on the target so when trying to pass arguments via environment variables, the test does not get them.

I saw https://github.com/flutter/flutter/issues/76852 which I think could help but are there other options available right now?

Solution

If you’re using the integration_test package, the test code can set global variables prior to running your app, and pull them from the environment specified using --dart-define

For example:

// In main.dart
var environment = 'production';

void main() {
  if (environment == 'development') {
    // setup configuration for you application
  }

  runApp(const MyApp());
}

// In your integration_test.dart
import 'package:my_app/main.dart' as app;

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  setUpAll(() {
    var testingEnvironment = const String.fromEnvironment('TESTING_ENVIRONMENT');
    if (testingEnvironment != null) {
      app.environment = testingEnvironment;
    }
  });

  testWidgets('my test', (WidgetTester tester) async {
    app.main();
    await tester.pumpAndSettle();
    
    // Perform your test
  });
}

then use the command line flutter test integration_test.dart --dart-define TESTING_ENVIRONMENT=development

Alternately, you could pull them from String.fromEnvironment directly in your app code.

Answered By – Jeff

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *