如何从Dart(Dartz)的任一类型中轻松提取Left或Right

我正在寻找从返回类型Either<Exception,Object>的方法中轻松提取值的方法。

我正在做一些测试,但是无法轻松测试我的方法的返回。

例如:

final Either<ServerException,Tokenmodel> result = await repository.getToken(...);

为了测试,我能够做到

expect(result,equals(Right(tokenmodelExpected))); // => OK

现在如何直接检索结果?

final Tokenmodel modelRetrieved = Left(result); ==> Not working..

我发现我必须像这样进行投射:

final Tokenmodel modelRetrieved = (result as Left).value; ==> But I have some linter complain,that telling me that I shouldn't do as to cast on object...

我也想测试异常,但是它不起作用,例如:

expect(result,equals(Left(ServerException()))); // => KO

所以我尝试了

expect(Left(ServerException()),equals(Left(ServerException()))); // => KO as well,because it says that the instances are different.
zhyl1109 回答:如何从Dart(Dartz)的任一类型中轻松提取Left或Right

我无法发表评论...但是也许您可以看看这个post。它不是相同的语言,但看起来却是相同的行为。

祝你好运。

,

在这里确定我的问题的解决方案:

提取/检索数据

final Either<ServerException,TokenModel> result = await repository.getToken(...);
result.fold(
 (exception) => DoWhatYouWantWithException,(tokenModel) => DoWhatYouWantWithModel
);

//Other way to 'extract' the data
if (result.isRight()) {
  final TokenModel tokenModel = result.getOrElse(null);
}

测试异常

//You can extract it from below,or test it directly with the type
expect(() => result,throwsA(isInstanceOf<ServerException>()));
,
  Future<Either<Failure,FactsBase>> call(Params params) async {
final resulting = await repository.facts();
return resulting.fold(
  (failure) {
    return Left(failure);
  },(factsbase) {
    DateTime cfend = sl<EndDateSetting>().finish;        
    List<CashAction> actions = factsbase.transfers.process(facts: factsbase,startDate: repository.today,finishDate: cfend); // process all the transfers in one line using extensions
    actions.addAll(factsbase.transactions.process(facts: factsbase,finishDate: cfend));
    for(var action in actions) action.account.cashActions.add(action); // copy all the CashActions to the Account.
    for(var account in factsbase.accounts) account.process(start: repository.today);
    return Right(factsbase);
  },);

}

本文链接:https://www.f2er.com/3150716.html

大家都在问