我正在嘗試為顫振應用程式撰寫單元測驗,但無法獲得合適的測驗用例
檢查回傳的函式: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'
我沒有得到什么?我應該從該功能中期待什么才能成功通過測驗?
uj5u.com熱心網友回復:
您直接使用resultwhich 實際上是一個包裝器并且具有Either<WeatherData, DataError>.
您需要使用fold結果上的方法解包值,然后相應地期望,因此在您的代碼中,您可以執行以下操作以使其作業:
final result = await sut.fetchWeatherByCity(city: "city");
result.fold(
(left) => fail('test failed'),
(right) {
expect(result, isInstanceOf<DataError>);
});
verifyNoMoreInteractions(mockWeatherApiService);
希望這可以幫助。
uj5u.com熱心網友回復:
您需要將期望值設為 Right(),或者提取實際值的右側。執行其中任何一個都將匹配,但實際上,您正在將包裝的值與未包裝的值進行比較。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523257.html
標籤:扑单元测试镖
上一篇:JUnit5TestExecutionListeners和中間容器
下一篇:為python程式撰寫測驗
