Skip to content

Instantly share code, notes, and snippets.

@danielgomezrico
Last active August 15, 2020 22:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielgomezrico/4a519ff8bbd57250b60fa761559772ea to your computer and use it in GitHub Desktop.
Save danielgomezrico/4a519ff8bbd57250b60fa761559772ea to your computer and use it in GitHub Desktop.
Flutter - Android - extensions to mock more easy on testing with mockito
// The abstractions
abstract class Result<T> {
}
class Success<T> extends Result<T> {
final T body;
Success(this.body);
}
class Failure<T> extends Result<T> {
final String cause;
Failure({this.cause});
}
class Session {
int userId;
}
class UserRepository {
Future<Result<Session>> login(String email, String password) {
// Do the Http call here and get the user id...
}
}
// The Mockito test extensions
extension ResultMock<T> on PostExpectation<Future<Result<T>>> {
// One for success
void thenSucceed(T body) {
var result = Result.success(body);
thenAnswer((realInvocation) => Future.value(result));
}
// One for failures
void thenFail([String message = 'mock-error']) {
var result = Failure(message);
thenAnswer((realInvocation) => Future.value(result));
}
}
// Abstractions
sealed class Result<T>
class Success<T>(val body: T) : Result<T>()
class Failure<T>(val cause: String) : Result<T>()
// Mockito extensions
fun <T> OngoingStubbing<Flowable<Result<T>>>.thenReturn(data: T): OngoingStubbing<Flowable<Result<T>>> {
return thenReturn(Flowable.just(Success(data)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment