Reputation: 182
I have a test for check an exception:
test('throws an exception if missing data', () async {
final client = MockClient();
final _apiService = ApiService(client, 'test/');
when(
client.post(
Uri.parse('test/user/auth_user'),
headers: {
'Content-Type': 'application/json',
},
body: json.encode({"email": '', "password": ''}),
),
).thenAnswer(
(_) async => http.Response(
'{"status": 400,"data": {"message": "Missing email or password fields"}}',
400,
),
);
expect(
await _apiService.login(email: '', password: ''),
isA<MissingDataException>(),
);
});
but is not working, this is the output of the test:
This is my exception:
class MissingDataException implements Exception {
String message;
MissingDataException(this.message);
}
I tried with
throwsException
and didn't work.
I also tried with
throwsA(TypeMatcher<MissingDataException>())
and also didn't work.
What I can do?
Thanks in advance.
Upvotes: 1
Views: 302
Reputation: 182
I finally found out that just pulling the await out of the function worked:
expect(
_apiService.login(email: '', password: ''),
throwsA(isA<MissingDataException>()),
);
Upvotes: 0
Reputation: 5333
Refactor this:
expect(
await _apiService.login(email: '', password: ''),
isA<MissingDataException>(),
);
To this:
final fn = () async => await _apiService.login(email: '', password: '');
expect(
fn,
throwsA(isA<MissingDataException>())
);
You need to pass a function reference to the expect
in order to validate the exception. Now, you are comparing the isA<MissingDataException>
with a result from login()
, but the exception won't be returned as a result, it should be handled.
Upvotes: 1