簡體   English   中英

如何從 flutter 中的 dartz package 為 Either<> 編寫測試

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM