如何从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.

回答:

好的,这里是我的问题的解决方案:

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>()));

以上是 如何从Dart(Dartz)中的任一类型轻松提取Left或Right 的全部内容, 来源链接: utcz.com/qa/417719.html

回到顶部