[英]How to extract Left or Right easily from Either type in Dart (Dartz)
[英]How to write tests for Either<> from dartz package in flutter
我正在尝试为 flutter 应用程序编写单元测试,但我无法让这个测试用例正常工作。
这是返回Future<Either<WeatherData, DataError>>
的 function:
@override
Future<Either<WeatherData, DataError>> fetchWeatherByCity({required String city}) async {
try {
var response = await apiService.fetchWeatherByCity(city: city);
if (response.statusCode == 200) {
return Left(WeatherData.fromJson(jsonDecode(response.body)));
} else {
return Right(DataError(title: "Error", description: "Desc", code: 0, url: "NoUrl"));
}
} catch (error) {
AppException exception = error as AppException;
return Right(DataError(
title: exception.title, description: exception.description, code: exception.code, url: exception.url));
}
}
这是我尝试编写单元测试的代码:
sut = WeatherRepositoryImpl(apiService: mockWeatherApiService);
test(
"get weather by city DataError 1 - Error 404 ",
() async {
when(mockWeatherApiService.fetchWeatherByCity(city: "city"))
.thenAnswer((_) async => Future.value(weatherRepoMockData.badResponse));
final result = await sut.fetchWeatherByCity(city: "city");
verify(mockWeatherApiService.fetchWeatherByCity(city: "city")).called(1);
expect(result, isInstanceOf<DataError>);
verifyNoMoreInteractions(mockWeatherApiService);
},
);
当我运行这个特定的测试时,我收到这个错误:
Expected: <Instance of 'DataError'>
Actual: Right<WeatherData, DataError>:<Right(Instance of 'DataError')>
Which: is not an instance of 'DataError'
我没有得到什么? 要使测试成功通过,我应该从 function 得到什么?
您需要将期望值设为 Right(),或者提取实际值的右侧。 执行其中任何一个都会匹配,但实际上,您是在比较包装值和未包装值。
您直接使用的result
实际上是一个包装器并且具有Either<WeatherData, DataError>
类型。
您需要在结果上使用fold
方法打开值,然后进行相应的期望,因此在您的代码中,您可以执行类似这样的操作以使其工作:
final result = await sut.fetchWeatherByCity(city: "city");
result.fold(
(left) => fail('test failed'),
(right) {
expect(result, isInstanceOf<DataError>);
});
verifyNoMoreInteractions(mockWeatherApiService);
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.