我希望从返回类型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.发布于 2019-11-18 08:37:16
好的,在这里,我的问题的解决方案:
提取/检索数据
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>()));发布于 2022-03-05 08:05:46
朋友,
只需创建像这样的dartz_x.dart。
import 'package:dartz/dartz.dart';
extension EitherX<L, R> on Either<L, R> {
R asRight() => (this as Right).value; //
L asLeft() => (this as Left).value;
}像那样使用。
import 'dartz_x.dart';
void foo(Either<Error, String> either) {
if (either.isLeft()) {
final Error error = either.asLeft();
// some code
} else {
final String text = either.asRight();
// some code
}
}发布于 2019-11-08 07:21:15
我不能发表评论..。但也许你可以看看这个post。这不是同一种语言,但看起来是同样的行为。
祝好运。
https://stackoverflow.com/questions/58734044
复制相似问题