mockito 如何在Flutter / Dart中实现getter或冻结数据类的方法

h43kikqp  于 2022-11-08  发布在  Flutter
关注(0)|答案(1)|浏览(179)

我有一个冻结的数据类,其中有一些字段。getter方法返回一个属性的嵌套元素,以便更容易访问。

@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();
}

我在一个测试中使用了Airport类,在那里调用了getter allIls。我不想用合法的数据填充runways,而是想直接stub getter方法allIls,并让它返回一个对象列表。
我尝试过:
模拟Airport类:class MockAirport extends Mock implements Airport {}
我的测试:

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

      expect(...);
    });

但是,这会产生以下错误:type 'Null' is not a subtype of type 'List<Ils>'MockAirport.allIls
我还尝试了一个“normal”方法来代替getter,得到了相同的结果:

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

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

你知道我能做什么吗?

0yycz8jy

0yycz8jy1#

看起来您在设置模拟时遗漏了一个步骤。
您需要在库中的某个位置添加GenerateMocksGenerateNiceMocks属性,以自动生成Airport模拟。我希望将该属性与我的测试放在同一个文件中,但这可能会导致在整个测试文件中重复模拟。在添加了该属性后,您可以使用build_runner生成模拟。
最后,在使用“normal”方法的第二个示例中,不需要在when语句中添加.call(),事实上,添加它会导致调用失败,它应该只为when(airport.allIls2()).thenReturn(ilsList)

相关问题