我希望从返回类型的方法中轻松提取值Either<Exception, Object>。
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>()));