Sub topic 14
Testing against different configurations
This chapter assumes you have read the earlier chapters of this tutorial. You should know how --dart-define and --dart-define-from-file work, what the AppConfig class looks like, and how --flavor and -t select an entrypoint. You should also be comfortable writing basic flutter_test unit and widget tests.
What needs testing
A flavored app has more failure modes than a single-environment app. A test suite that only runs with default settings can pass while a staging or prod build is broken. The problems fall into three groups:
- Logic that depends on configuration. Code that builds URLs, enables logging, or hides debug UI behaves differently per environment.
- The configuration itself. A key missing from
config/prod.jsondoes not fail the build.String.fromEnvironmentquietly returns its default value or an empty string. - The native flavor setup. A wrong application ID suffix or a missing Firebase file only shows up when you build that flavor.
Each group needs a different kind of test, and they run at different speeds.
| Layer | What it proves | How configuration arrives | Speed |
|---|---|---|---|
| Unit test | Logic is correct for a given `AppConfig` | Constructed directly in the test | Milliseconds |
| Config file test | Every environment file has the same keys | Read from `config/*.json` | Milliseconds |
| Widget test | UI reacts to the config it is given | Passed to the widget | Seconds |
| Integration test | A real flavor build starts and works | `--flavor` and `--dart-define-from-file` | Minutes |
Prefer injected configuration over compile-time lookups
AppConfig.fromEnvironment is a static const. Its value is fixed when the test is compiled, so a test cannot change it while running. Any code that reads AppConfig.fromEnvironment directly cannot be tested against a second environment in the same test run.
The fix is to read fromEnvironment once, in the entrypoint, and pass the AppConfig down to everything else. Tests then build whatever AppConfig they need.
This chapter uses a small ApiClient as the example. It builds endpoint URLs from the configured base URL.
// lib/api_client.dart
import 'app_config.dart';
class ApiClient {
const ApiClient(this.config);
final AppConfig config;
Uri endpoint(String path) {
final base = Uri.parse(config.apiBaseUrl);
return base.replace(path: '${base.path}/$path'.replaceAll('//', '/'));
}
}The class never touches the environment. It receives the config in its constructor, so it works with any environment.
Unit tests with explicit configs
Create one AppConfig per environment inside the test file. The values are plain strings and booleans, so there is nothing to compile in.
// test/api_client_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/api_client.dart';
import 'package:my_app/app_config.dart';
void main() {
const dev = AppConfig(
apiBaseUrl: 'https://api.dev.example.com',
enableLogging: true,
);
const prod = AppConfig(
apiBaseUrl: 'https://api.example.com/v2',
enableLogging: false,
);
group('ApiClient.endpoint', () {
test('uses the dev host', () {
expect(
const ApiClient(dev).endpoint('users').toString(),
'https://api.dev.example.com/users',
);
});
test('keeps a path prefix from the base URL', () {
expect(
const ApiClient(prod).endpoint('users').toString(),
'https://api.example.com/v2/users',
);
});
});
}Run it with plain flutter test. No --dart-define flags are needed, because nothing in the test reads the environment.
The second test covers an edge case. A prod base URL may carry a path prefix such as /v2, while dev does not. Environments differ in shape as well as in value, and tests are the cheapest place to catch that.
Testing the compile-time defaults
You may still want to test AppConfig.fromEnvironment itself. Its value depends on the flags given to flutter test, so write assertions that hold for every valid environment instead of asserting one specific URL.
// test/app_config_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/app_config.dart';
void main() {
test('fromEnvironment yields a usable https base URL', () {
final uri = Uri.parse(AppConfig.fromEnvironment.apiBaseUrl);
expect(uri.scheme, 'https');
expect(uri.host, isNotEmpty);
});
}You can then run the same test once per environment. The --dart-define-from-file flag works with flutter test:
flutter test test/app_config_test.dart --dart-define-from-file=config/dev.json
flutter test test/app_config_test.dart --dart-define-from-file=config/prod.jsonA prod file with a typo such as http:// or an empty API_BASE_URL makes the second command fail. A plain flutter test run would not catch it.
Validating the config files
The test above checks values after they have been compiled in. A second test can check the JSON files directly. Its main job is to make sure all environments define the same set of keys, so adding a key to dev.json and forgetting prod.json fails the build.
// test/config_files_test.dart
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
Map<String, dynamic> load(String name) {
final text = File('config/$name.json').readAsStringSync();
return jsonDecode(text) as Map<String, dynamic>;
}
final environments = ['dev', 'prod'];
final reference = load('dev').keys.toSet();
for (final name in environments) {
test('config/$name.json has the same keys as dev.json', () {
expect(load(name).keys.toSet(), reference);
});
test('config/$name.json contains only string values', () {
expect(load(name).values, everyElement(isA<String>()));
});
}
}flutter test runs with the package root as the working directory, so the relative path config/ resolves correctly. The string check matters because bool.fromEnvironment reads the text "true". A JSON boolean can be easy to write by mistake, so the test catches it.
Add each new environment name to the environments list when you create its file.
Widget tests
A widget test needs a config only if the widget uses one. Pass it as a constructor argument, the same way as for ApiClient. Here is a small widget that shows the host name outside prod:
// lib/config_badge.dart
import 'package:flutter/material.dart';
import 'app_config.dart';
class ConfigBadge extends StatelessWidget {
const ConfigBadge({super.key, required this.config});
final AppConfig config;
@override
Widget build(BuildContext context) {
final host = Uri.parse(config.apiBaseUrl).host;
if (!config.enableLogging) {
return const SizedBox.shrink();
}
return Text('Backend: $host');
}
}// test/config_badge_test.dart
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/app_config.dart';
import 'package:my_app/config_badge.dart';
void main() {
testWidgets('shows the host when logging is on', (tester) async {
await tester.pumpWidget(const MaterialApp(
home: ConfigBadge(
config: AppConfig(
apiBaseUrl: 'https://api.dev.example.com',
enableLogging: true,
),
),
));
expect(find.text('Backend: api.dev.example.com'), findsOneWidget);
});
testWidgets('shows nothing when logging is off', (tester) async {
await tester.pumpWidget(const MaterialApp(
home: ConfigBadge(
config: AppConfig(
apiBaseUrl: 'https://api.example.com',
enableLogging: false,
),
),
));
expect(find.textContaining('Backend'), findsNothing);
});
}Both environments run in the same flutter test invocation, with no flags.
Integration tests on a real flavor
Unit and widget tests never load the native flavor setup. They run on the host machine with the Flutter test framework, so the Gradle productFlavors and iOS schemes are not involved. An integration test runs on a device or emulator and does use them.
The test imports the flavor's entrypoint, which hard-codes or reads its configuration, and starts the real app.
// integration_test/app_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:my_app/main_dev.dart' as app;
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('dev flavor starts', (tester) async {
app.main();
await tester.pumpAndSettle();
expect(find.byType(MaterialApp), findsOneWidget);
});
}Run it with the flavor and config file that match the entrypoint:
flutter test integration_test/app_test.dart \
--flavor dev \
--dart-define-from-file=config/dev.json \
-d emulator-5554The -t flag is not used here. The test file is the entry point, and the import line decides which main runs. To cover staging as well, add a second test file that imports main_staging.dart and run it with --flavor staging.
Handling appFlavor in tests
appFlavor is null in a plain flutter test run because no --flavor was given. Code that branches on it behaves as if there were no flavor, which is often not what you want to verify.
Two habits keep this manageable:
- Branch on
AppConfigin your logic and treatappFlavoras information for display or diagnostics only. - When a test must cover flavor-specific behavior, run it as an integration test with
--flavor, whereappFlavorhas a real value.
Running everything in CI
Fast tests need no devices, so they can run on every push. Put the per-environment checks in a loop, so adding an environment needs one change:
flutter test
for env in dev staging prod; do
flutter test test/app_config_test.dart \
--dart-define-from-file=config/$env.json
doneIntegration tests need an emulator or simulator and take longer. Run them on a schedule or before a release, once per flavor. Building each flavor in CI, as described in the earlier chapter on tooling and CI, also checks that the Gradle and Xcode flavor setup still compiles.
Common mistakes
- Reading
AppConfig.fromEnvironmentinside a class under test. The test can no longer choose the environment. Inject the config instead. - Asserting one exact URL in
app_config_test.dart. The test then passes only for one environment file. Assert properties that every environment must have. - Forgetting
--dart-define-from-fileonflutter test. The defines from yourflutter runcommand do not carry over, so tests silently see the defaults. - Treating a green unit-test run as proof that prod builds. Unit tests do not touch Gradle or Xcode. Build each flavor at least in CI.
Exercise
Your team adds a new key, SENTRY_ENABLED, to config/dev.json but forgets config/prod.json. The unit tests all pass and the prod build compiles. Which test from this chapter would have caught the mistake, and why did the other tests miss it?
Show answer
The config file test (test/configfilestest.dart) would have caught it, because it compares the key set of every config/*.json file against dev.json and fails when prod.json lacks SENTRY_ENABLED. The unit and widget tests missed it because they build AppConfig objects directly and never read the JSON files. The prod build compiled because a missing --dart-define key is not an error: String.fromEnvironment and bool.fromEnvironment return their default values instead.
Exercise
A test imports main_dev.dart but is run with --flavor prod --dart-define-from-file=config/prod.json. What is built and why is it a problem?
Show answer
The app is built with the prod flavor's native settings (application ID, app name, signing and any prod service files) but starts the dev entrypoint with hard-coded dev settings. The test may pass, but it checks a combination that is never released. The import, the --flavor value and the config file should all name the same environment.