Skip to content

Instantly share code, notes, and snippets.

@cdmunoz
Last active July 24, 2023 00:56
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 cdmunoz/a2983cc80b13928f64fb51a85aef09d4 to your computer and use it in GitHub Desktop.
Save cdmunoz/a2983cc80b13928f64fb51a85aef09d4 to your computer and use it in GitHub Desktop.
/// mocking the PostExpectation with a Future
extension FutureMock<T> on PostExpectation<Future<T>> {
void thenFuture(T body) {
thenAnswer((realInvocation) => Future.value(body));
}
}
/// we use Result objet similar than a monad which returns a success, a failure, etc
/// this extension mocks a Result of success, failure or in order
extension ResultMock<T> on PostExpectation<Future<Result<T>>> {
void thenSucceed(T body) {
final result = Result.success(body);
thenAnswer((realInvocation) => Future.value(result));
}
void thenFail([String message = 'mock-error']) {
final result = Result<T>.failureWithMessage(message);
thenAnswer((realInvocation) => Future.value(result));
}
void thenResultInOrder(List<Result<T>> results) {
final availableResults = Queue.of(results);
thenAnswer((_) => Future.value(availableResults.removeFirst()));
}
void thenFailWithCause(Error cause) {
final result = Result<T>.failure(cause);
thenAnswer((realInvocation) => Future.value(result));
}
}
/// in some scenarios we use Streams, then to mock a stream response of any type
/// we use this extension
extension StreamMock<T> on PostExpectation<Stream<T>> {
void thenStream(T body) {
thenAnswer((realInvocation) => Stream.value(body));
}
void thenEmpty() {
thenAnswer((realInvocation) => const Stream.empty());
}
}
/// this mocks a response from an endpoint comsumption or a failure
/// we use a helper `buildSuccessResponse` method to build a response
extension ResponseResultMock<T> on PostExpectation<Future<Response<T>>> {
void thenSucceed(T body) {
thenAnswer((realInvocation) => Future.value(buildSuccessResponse(body)));
}
void thenFail({String message = 'mock-error', int statusCode = 400}) {
thenAnswer(
(realInvocation) => Future.value(
buildFailureResponse(message, code: statusCode),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment