2

我正在使用 Wea​​therAPI 开发一个应用程序。我目前无法实施一些工作测试。我尝试遵循 ResoCoders 指南(https://resocoder.com/2019/11/29/bloc-test-tutorial-easier-way-to-test-blocs-in-dart-flutter/)并实际实现了所有状态, blocs(我用 Cubit 代替)、类、函数……几乎相同。

这是我的测试代码:

blocTest<WeatherCubit, WeatherBaseState>(
      'Cubit emits WeatherLoaded',
      build: () {
        return WeatherCubit(weatherRepository: mockWeatherRepository);
      },
      act: (WeatherCubit cubit) => cubit.getWeather(),
      expect: () => [
        WeatherLoaded(
            temperature: temperature,
            ...
            lat: lat,
            lon: lon)
      ],
    );

这就是我从调试控制台得到的错误消息:

Expected: [Instance of 'WeatherLoaded']
  Actual: [Instance of 'WeatherLoaded']
   Which: at location [0] is <Instance of 'WeatherLoaded'> instead of <Instance of 'WeatherLoaded'>

WARNING: Please ensure state instances extend Equatable, override == and hashCode, or implement Comparable.
Alternatively, consider using Matchers in the expect of the blocTest rather than concrete state instances.

我尝试使用 Matcher,但不太了解如何使用它。

如果问题出在这里,我的 WeatherCubit 实现:

class WeatherCubit extends Cubit<WeatherBaseState> {
  final IWeatherRepository weatherRepository; //IWeatherRepository is interface

  WeatherCubit({required this.weatherRepository})
      : super(LoadingWeather()); // I use LoadingWeather as initial state


  Future<void> getWeather() async {
    final Position location = await weatherRepository.determinePosition();
    final WeatherData data = await weatherRepository.getWeather(
        lat: location.latitude, 
        lon: location.longitude); 
    final WeatherLoaded weatherLoaded = WeatherLoaded(
        temperature: data.temperature,
        ...
        lat: data.lat, 
        lon: data.lon); 
    emit(weatherLoaded); 
  }
}
4

1 回答 1

2

如果您尝试测试类型,则可以使用isA匹配器。

expect: () => [isA<WeatherLoaded>()];

如果您尝试比较返回对象的值,您需要使用Equatable包,或手动覆盖 Cubit 中的 hashCode 和 == 运算符。

于 2021-05-05T17:48:42.667 回答