飞镖/颤动测试肘,比较预期和实际的问题

Cof*_*tte 5 dart flutter bloc bloc-test

我正在开发一个使用 Wea​​therAPI 的应用程序。我目前无法实施一些工作测试。我尝试遵循 ResoCoders 指南(https://resocoder.com/2019/11/29/bloc-test-tutorial-easier-way-to-test-blocs-in-dart-flutter/)并实际实现了所有状态,块(我用 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)
      ],
    );
Run Code Online (Sandbox Code Playgroud)

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

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.
Run Code Online (Sandbox Code Playgroud)

我尝试使用 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); 
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 4

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

expect: () => [isA<WeatherLoaded>()];
Run Code Online (Sandbox Code Playgroud)

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