Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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