I have these 2 tests:
void main() {
group('...', () {
testWidgets('Should ... when the OS is macOS', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
platform: TargetPlatform.macOS,
),
));
...
assert(Theme.of(context).platform...); // platform is android!!
});
testWidgets('Should ... when the OS is windows', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
platform: TargetPlatform.windows,
),
));
...
assert(Theme.of(context).platform...); // platform is android!!
});
});
}
I overrided the platform in the theme of MaterialApp explicitly as per the docs:
In a test environment, the platform returned is TargetPlatform.android regardless of the host platform. (Android was chosen because the tests were originally written assuming Android-like behavior, and we added platform adaptations for other platforms later). Tests can check behavior for other platforms by setting the platform of the Theme explicitly to another TargetPlatform value, or by setting debugDefaultTargetPlatformOverride.
I also tried setting it via debugDefaultTargetPlatformOverride, like this:
void main() {
group('...', () {
testWidgets('Should ... when the OS is macOS', (WidgetTester tester) async {
// set the OS to macOS
debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
await tester.pumpWidget(const MaterialApp());
await tester.pumpAndSettle();
BuildContext context = tester.element(find.byType(MaterialApp));
assert(Theme.of(context).platform...); // Works, platform is macOS
// reset the default target platform
debugDefaultTargetPlatformOverride = null;
});
testWidgets('Should ... when the OS is windows', (WidgetTester tester) async {
// set the OS to windows
debugDefaultTargetPlatformOverride = TargetPlatform.windows;
await tester.pumpWidget(const MaterialApp());
await tester.pumpAndSettle();
BuildContext context = tester.element(find.byType(MaterialApp));
assert(Theme.of(context).platform...); //Platform is still macOS!!
// reset the default target platform
debugDefaultTargetPlatformOverride = null;
});
});
}
But in the code above the first test only passes but the second fails bcz the platform resetting is not working and the platform is still macOS (due to the first test).
What am I doing wrong?