1

The flutter package easy_localization has an extention method on the BuildContext which looks like this:

  Locale get deviceLocale => EasyLocalization.of(this)!.deviceLocale;

I wish to mock this using Mocktail.

I tried:

import 'package:mocktail/mocktail.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:test/test.dart';

class MockBuildContext extends Mock implements BuildContext {}

void main() {
  test("Sample test", () {
    final context = MockBuildContext();
    when(() => context.deviceLocale).thenReturn(const Locale('en', 'US'));
    expect(Locale('en', 'US'), context.deviceLocale);
  });
}

However this throws an error: type 'Locale' is not a subtype of type '_EasyLocalizationProvider?'. I am assuming this happens because we are (unsuccessfully) trying to mock an Extension method and that the original method is called instead.

How can I mock the extension method to get the desired result?

Rudy
  • 437
  • 2
  • 7
  • 1
    You can't mock an extension method. Extension methods are resolved *statically* (at compile-time), but mocks depend on virtual (runtime) dispatch. – jamesdlin Oct 31 '22 at 17:01
  • @jamesdlin Yeah that makes it very difficult. I was hoping there was some "hacky" way to accomplish this, like for example creating a mixin with the same function name and overriding the extension method in the mocked instance or something similar – Rudy Nov 01 '22 at 07:40
  • @Raida Not yet. I re-wrote the code instead – Rudy Dec 15 '22 at 11:32

0 Answers0