【问题标题】:Flutter how to test Either<Failure,List<Object>>Flutter 如何测试 Either<Failure,List<Object>>
【发布时间】:2022-11-10 23:09:08
【问题描述】:

它似乎与 matcher 具有相同的值,但仍然无法通过测试,可能是因为内存地址的东西。任何人都可以让我知道当列表在 Either<< Right >> 中时如何测试结果

test('get board list from remote data source', () async {
   when(mockBoardRemoteDataSource.getBoards())
       .thenAnswer((_) async => tBoardModels);

   final result = await repository.getBoards();

   verify(mockBoardRemoteDataSource.getBoards());
   expect(result, equals(Right(toBoards)));   
   // Either<Failure, List<BoardInfo>> result;
   // (new) Right<dynamic, List<BoardInfo>> Right(List<BoardInfo> _r)
});

//console result

Expected: Right<dynamic, List<BoardInfo>>:<Right([_$_BoardInfo(1, name1, address1), _$_BoardInfo(2, name2, address2)])>
Actual: Right<Failure, List<BoardInfo>>:<Right([_$_BoardInfo(1, name1, address1), _$_BoardInfo(2, name2, address2)])>
    
package:test_api                                                                   expect
package:flutter_test/src/widget_tester.dart 455:16                                 expect
test\features\nurban_honey\data\repositories\board_repository_impl_test.dart 58:9  main.<fn>.<fn>.<fn>

//BoardInfo Implementation

import 'package:equatable/equatable.dart';
import 'package:freezed_annotation/freezed_annotation.dart';

part 'board_info.freezed.dart';

@freezed
class BoardInfo extends Equatable with _$BoardInfo {
  BoardInfo._();
  factory BoardInfo(int id, String name, String address) = _BoardInfo;

  @override
  List<Object?> get props => [id, name, address];
}

【问题讨论】:

    标签: flutter-test either


    【解决方案1】:

    我通过这样做使测试通过:

    result.fold(
           (l) => null,
           (resultR) => Right(toBoards)
               .fold((l) => null, (matcherR) => expect(resultR, matcherR)));
    

    有更好的方法吗?

    【讨论】:

    • 或者这个:result.fold((l) => null, (r) => expect(r, toBoards));
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    感谢杰,他的回答帮助我做出了决定。

    这就是我进行测试的方式:

    // Act
    var results = (await repository.fetch()).fold(
        (failure) => failure,
        (response) => response,
    );
    

    然后我做了一个类型期望,与我的用例中声明的失败类型相匹配:

    在成功执行的情况下

    // Assert
    expect(results, isA<ResultType>());
    

    在失败预期的情况下

    // Assert
    expect(results, isA<FailureType>());
    

    整个测试用例如下所示

    test('On successful execution, should returns a SuccessResultType', () async {
      
      // Arrange
      repository = MyUseCaseRepository();
    
      // Act
      var results = (await repository.fetch()).fold(
        (failure) => failure,
        (response) => response,
      );
    
      // Assert
      expect(results, isA<SuccessResultType>());
    });
    

    我希望这种方法可以帮助任何人!

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 1970-01-01
      • 2019-10-23
      • 2022-09-30
      • 2023-01-25
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多