Home > Net >  How to stub getter or a method of freezed dataclass in Flutter / Dart
How to stub getter or a method of freezed dataclass in Flutter / Dart

Time:08-10

I have a freezed data class with some fields. A getter method returns nested elements of one attribute for easier access.

@freezed
class Airport with _$Airport {
  const Airport._();
  const factory Airport({
    required String identifier
    required String type,
    required List<Runway> runways,
  }) = _Airport;

  List<Ils> get allIls => runways
      .map((runway) => runway.allIls)
      .expand((ils) => ils)
      .toList();
}

I use the Airport class inside a test where the getter allIls is called. I don't want to fill runways with legit data, instead I directly want to stub the getter method allIls and have it return a list of objects.

What I tried:

Mock the Airport class: class MockAirport extends Mock implements Airport {}

My test:

    test('',
        () async {
      final airport = MockAirport();
      final ilsList = [ils1, il2];
      when(airport.allIls).thenReturn(ilsList);

      expect(...);
    });

However, this gives me the following error: type 'Null' is not a subtype of type 'List<Ils>'MockAirport.allIls

I have also tried a "normal" method instead of a getter, with the same results:

  List<Ils> allIls2() => runways
      .map((runway) => runway.allIls)
      .expand((ils) => ils)
      .toList();
...

when(airport.allIls2.call()).thenReturn(ilsList);

Any idea what I could do?

CodePudding user response:

It looks like you missed a step in setting up your Mocks.

You need to add the GenerateMocks or GenerateNiceMocks attribute somewhere in your library to auto-generate your Airport mocks. I like to have the attribute in the same file as my test, though that can lead to repeated mocks throughout your test files. After you have the attribute, you generate the mock using build_runner.

Lastly, in your second example with the "normal" method, you don't need to add the .call() to your when statement. In fact, adding that will cause the call to fail. It should instead just be when(airport.allIls2()).thenReturn(ilsList).

  • Related