flutter / flutter

Flutter makes it easy and fast to build beautiful apps for mobile and beyond
https://flutter.dev
BSD 3-Clause "New" or "Revised" License
165.58k stars 27.34k forks source link

Provide a way to define a custom TestWidgetsFlutterBinding that overrides the defaultBinaryMessenger #104156

Open Nobler opened 2 years ago

Nobler commented 2 years ago

Use case

In my case, I override the defaultBinaryMessenger just like TestDefaultBinaryMessengerBinding is doing:

mixin BinaryMessengerBinding on ServicesBinding {
  @override
  void initInstances() {
    super.initInstances();

    _instance = this;
  }

  static BinaryMessengerBinding? get instance => _instance;
  static BinaryMessengerBinding? _instance;

  @override
  BinaryMessenger createBinaryMessenger() => MyCustomBinaryMessenger();
}

When I want to test BinaryMessengerBinding in testWidget(), there is no proper way to define a custom TestWidgetsFlutterBinding(test framework needs), because the definition of TestWidgetsFlutterBinding mixed with TestDefaultBinaryMessengerBinding which needs the subclass/mixin also do the same thing (I guess, but am not sure) like:

mixin BinaryMessengerBinding on TestDefaultBinaryMessengerBinding {
  ...

  @override
  TestDefaultBinaryMessenger createBinaryMessenger() => ...
}

Proposal

So, is there any way to test BinaryMessengerBinding above? If not, could please provide a way to define a custom TestWidgetsFlutterBinding that overrides the defaultBinaryMessenger but will not break the test behavior.

darshankawar commented 2 years ago

@Nobler Thanks for the report. Does this issue resemble your case ? https://github.com/flutter/flutter/issues/94123

If not, have you already tried using WidgetsFlutterBinding.ensureInitialized() as the first code just after main() to see if it helps ?

Nobler commented 2 years ago

94123

Thanks for replying.

Production codes work fine just like you said:

class CustomWidgetFlutterBinding extends WidgetsFlutterBinding
    with BinaryMessengerBinding {
  static WidgetsBinding ensureInitialized() {
    if (WidgetsBinding.instance == null) {
      CustomWidgetFlutterBinding();
    }
    return WidgetsBinding.instance!;
  }
}

void main() {
  CustomWidgetFlutterBinding.ensureInitialized();

  runApp();
}

My question is that the implementation of TestWidgetsFlutterBinding in flutter_test package does not support testing BinaryMessengerBinding.

darshankawar commented 2 years ago

Thanks for the update.