Last active
July 24, 2023 00:56
-
-
Save cdmunoz/a2983cc80b13928f64fb51a85aef09d4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/// 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