[英]Dart / Flutter test cubit, problem with comparing expected and actual
I'm working on an app using a WeatherAPI.我正在使用 WeatherAPI 开发一个应用程序。 I currently fail to implement some working tests.
我目前无法实施一些工作测试。 I tried to follow ResoCoders Guide ( https://resocoder.com/2019/11/29/bloc-test-tutorial-easier-way-to-test-blocs-in-dart-flutter/ ) and actually implemented all states, blocs (I used Cubit instead), classes, functions, ... almost the same.
我尝试遵循 ResoCoders 指南( https://resocoder.com/2019/11/29/bloc-test-tutorial-easier-way-to-test-blocs-in-dart-flutter/ )并实际实现了所有状态, blocs(我用 Cubit 代替)、类、函数……几乎相同。
This is my test's code:这是我的测试代码:
blocTest<WeatherCubit, WeatherBaseState>(
'Cubit emits WeatherLoaded',
build: () {
return WeatherCubit(weatherRepository: mockWeatherRepository);
},
act: (WeatherCubit cubit) => cubit.getWeather(),
expect: () => [
WeatherLoaded(
temperature: temperature,
...
lat: lat,
lon: lon)
],
);
And that's my error massage from the debug console:这就是我从调试控制台得到的错误消息:
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.
I tried to use a Matcher but did not quite get how to use it.我尝试使用 Matcher,但不太了解如何使用它。
In case the problem lies here, my implementation of the WeatherCubit:如果问题出在这里,我的 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);
}
}
You can use the isA matcher if you are trying to test the type.如果您尝试测试类型,则可以使用isA匹配器。
expect: () => [isA<WeatherLoaded>()];
If you are trying to compare the values of the returned object you need to either use the Equatable package, or manually override the hashCode and == operator in your Cubit.如果您尝试比较返回的 object 的值,您需要使用Equatable package,或手动覆盖 Cubit 中的 hashCode 和 == 运算符。
As mentioned above you can use the isA, matcher.如上所述,您可以使用 isA,匹配器。 To check the properties, try using the having method available in this matcher.
要检查属性,请尝试使用此匹配器中可用的方法。
expect: () => [isA<WeatherLoaded>()..having((p0) => p0.temprature, "description", "30")];
Here "30" is the expected value.这里“30”是期望值。
Like this, you can check all the properties.像这样,您可以检查所有属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.