im testing this method here
@override
Future<List<dynamic>> makeRequest(ApiRequestParams params) async {
try {
final request = await _repository.get(params);
if (request == null) {
throw Exception('Whoops');
}
// Go on...
} catch (e) {
rethrow;
}
}
When repository itself doesn’t throw, but returns null
, I want to makeRequest
to throw
. But when testing it, I assumme that since I’m not throwing in the when
method, makeRequest
is throwing and stopping there. So is there a way that I can throw
something outside of when
and catching it?
My test block
test('When api returns null, should throw exception', () async {
// stub
when(() => repository.get(requestParams))
.thenAnswer((_) => Future.value(null));
// arrange
final result = await usecase.makeRequest(requestParams);
// assert
verify(() => repository.get(requestParams)).called(1);
expect(result, throwsA(isA<Exception>()));
});
});
2
Answers
Solution
I found the solution when reading this question
Doesn't work:
Works:
Not sure why but using
expectLater
instead ofawait
and thenexpect
works.In Mocktail, you can catch exceptions that were not thrown in a
when
method by using thethenThrow
method to specify the exception that should be thrown when the mocked method is called with certain parameters. If the method is called with different parameters, it will throw an exception by default.Here’s an example of how you can catch exceptions that were not thrown in a
when
method using Mocktail in Flutter:In this example:
fetchData
method ofSomeService
class using thewhen
method. WhenfetchData
is called with1
, it will return42
. WhenfetchData
is called with2
, it will throw an exception.fetchData
method by calling it with valid and invalid parameters. We expect that calling it with1
will return42
, and calling it with2
will throw an exception as specified in thewhen
method.