如何从 Dart (Dartz) 中的任一种类型中轻松提取左或右

Mau*_*ice 17 unit-testing either dart flutter

我希望从返回类型的方法中轻松提取值Either<Exception, Object>

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

例如:

final Either<ServerException, TokenModel> result = await repository.getToken(...);
Run Code Online (Sandbox Code Playgroud)

为了测试我能够做到这一点

expect(result, equals(Right(tokenModelExpected))); // => OK
Run Code Online (Sandbox Code Playgroud)

现在如何直接检索结果?

final TokenModel modelRetrieved = Left(result); ==> Not working..
Run Code Online (Sandbox Code Playgroud)

我发现我必须这样投:

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...
Run Code Online (Sandbox Code Playgroud)

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

expect(result, equals(Left(ServerException()))); // => KO
Run Code Online (Sandbox Code Playgroud)

所以我试过这个

expect(Left(ServerException()), equals(Left(ServerException()))); // => KO as well, because it says that the instances are different.
Run Code Online (Sandbox Code Playgroud)

Mau*_*ice 26

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

提取/检索数据

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);
}
Run Code Online (Sandbox Code Playgroud)

测试异常

//You can extract it from below, or test it directly with the type
expect(() => result, throwsA(isInstanceOf<ServerException>()));
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 17

朋友们,

只需像这样创建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;
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用。

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
  }
}
Run Code Online (Sandbox Code Playgroud)