Last active
August 15, 2020 22:14
-
-
Save danielgomezrico/4a519ff8bbd57250b60fa761559772ea to your computer and use it in GitHub Desktop.
Flutter - Android - extensions to mock more easy on testing with mockito
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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