Skip to content

Instantly share code, notes, and snippets.

@Ian-FR
Created June 7, 2022 11:39
Show Gist options
  • Save Ian-FR/79aab3534ecf83d8a68efc27b340f7d0 to your computer and use it in GitHub Desktop.
Save Ian-FR/79aab3534ecf83d8a68efc27b340f7d0 to your computer and use it in GitHub Desktop.
Either functional approach
import 'package:flutter_test/flutter_test.dart';
import 'package:oakberry_superapp/app/error/failures.dart';
abstract class Result<L, R> {
static Result<L, R> failure<L, R>(L error) => _Left(error);
static Result<L, R> success<L, R>(R data) => _Right(data);
bool get isFailure => this is _Left<L, R>;
bool get isSuccess => this is _Right<L, R>;
T handle<T>(T Function(L) fnL, T Function(R) fnR);
}
class _Left<L, R> extends Result<L, R> {
final L value;
_Left(this.value);
@override
T handle<T>(T Function(L) fnL, T Function(R) fnR) {
return fnL.call(value);
}
}
class _Right<L, R> extends Result<L, R> {
final R value;
_Right(this.value);
@override
T handle<T>(T Function(L) fnL, T Function(R) fnR) {
return fnR.call(value);
}
}
class _TestData {
final String body;
_TestData(this.body);
}
class FooFailure extends Failure {}
void main() {
Result<Failure, _TestData> Function() build([bool throws = false]) {
if (throws) return () => Result.failure(FooFailure());
return () => Result.success(_TestData('body'));
}
test('sut success', () {
final sut = build();
final response = sut.call();
final result = response.handle((l) => l, (r) => r);
expect(result, isA<_TestData>());
expect(response.isSuccess, true);
expect(response.isFailure, false);
});
test('sut failure', () {
final sut = build(true);
final response = sut.call();
final result = response.handle((l) => l, (r) => r);
expect(result, isA<FooFailure>());
expect(response.isSuccess, false);
expect(response.isFailure, true);
});
test('should return success', () {
final Result<Failure, _TestData> response =
Result.success(_TestData('body'));
final result = response.handle((failure) => failure, (data) => data);
expect(result, isA<_TestData>());
expect(response.isSuccess, true);
expect(response.isFailure, false);
});
test('should return failure', () {
final Result<Failure, _TestData> response = Result.failure(FooFailure());
final result = response.handle((failure) => failure, (data) => data);
expect(result, isA<FooFailure>());
expect(response.isSuccess, false);
expect(response.isFailure, true);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment