I want to unit test and check a method makes correct http request. So I create the bellow test:
class MockRequest extends Mock implements http.Request {}
then
test('make correct http request', () async {
final uri = baseUri.replace(path: 'account/send_email');
final response = MockResponse();
when(
() => response.statusCode,
).thenReturn(200);
when(
() => response.stream,
).thenAnswer(
(_) => http.ByteStream.fromBytes('OK'.codeUnits),
);
final request = MockRequest();
when(
() => request.method,
).thenReturn('GET');
when(
() => request.body,
).thenReturn('{"email":"$validEmail"}');
when(
() => request.headers,
).thenReturn({
'Content-Type': 'text/plain',
});
when(
() => request.url,
).thenReturn(uri);
when(() => client.send(any())).thenAnswer((_) async => response);
try {
await sut.sendEmail(validEmail);
} catch (_) {}
verify(() => client.send(request)).called(1);
});
and here is my method:
Future<void> sendEmail(String email) async {
if (!EmailValidator.validate(email)) throw InvalidEmailFormatException();
final requestUrl = baseUri.replace(path: '/account/send_email');
final request = http.Request(RequestMethod.get.method, requestUrl);
request.headers.clear();
request.headers.addAll({"Content-type": "text/plain"});
request.body = '{"email":"$email"}';
try {
final response = await _client.send(request);
if (response.statusCode != 200) {
throw HttpException(
'Response statuse code = ${response.statusCode}, Reason phrase = ${response.reasonPhrase}',
uri: requestUrl);
}
final responseBodyString = await response.stream.bytesToString();
final reponseJson =
jsonDecode(responseBodyString) as Map<String, dynamic>;
final code = reponseJson['code'];
if (code != 200) {
throw ServerException(code, uri: requestUrl);
}
} on SocketException {
rethrow;
} on FormatException {
rethrow;
}
}
I get the No matching calls. All calls: MockClient.send(GET https://test.webapi.odinpool.com:1989/account/send_email)
message. What did I do wrong?
I tought to use Equatable
package to compare request both in the actual method and in the test, but i don't know how to use equatable with mock object.Since the request object didn't inject to API class so how we can ensure that this two request object was same?