我试图为一个颤振应用程序编写单元测试,但我无法让这个测试用例正确工作。
下面是返回Future<Either<WeatherData, DataError>>的函数
@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'我在这里得不到什么?我应该从函数中期望什么才能成功通过测试?
发布于 2022-10-28 06:35:52
您直接使用的是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);希望这能有所帮助。
发布于 2022-10-27 18:20:56
您需要将期望值设为Right(),或者提取实际值的右侧。执行这两种方法都是匹配的,但实际上,您正在比较包装值和未包装值。
https://stackoverflow.com/questions/74221498
复制相似问题