Làm sao để mock network trong unit test Flutter?
Làm sao để mock network trong unit test Flutter?
Nguyên tắc: code gọi API không được tạo HTTP client bên trong, mà nhận client (hoặc repository) từ bên ngoài (dependency injection). Khi test, truyền bản giả vào.
MockClient của package httpimport 'package:http/http.dart' as http;
import 'package:http/testing.dart';
class UserApi {
UserApi(this._client);
final http.Client _client;
Future<User> getUser(int id) async {
final res = await _client.get(Uri.parse('https://api.example.com/users/$id'));
if (res.statusCode != 200) throw ApiException(res.statusCode);
return User.fromJson(jsonDecode(res.body));
}
}
test('trả về User khi API trả 200', () async {
final client = MockClient((request) async {
expect(request.url.path, '/users/1');
return http.Response('{"id":1,"name":"An"}', 200);
});
final user = await UserApi(client).getUser(1);
expect(user.name, 'An');
});
test('ném ApiException khi API trả 500', () async {
final api = UserApi(MockClient((_) async => http.Response('error', 500)));
expect(api.getUser(1), throwsA(isA<ApiException>()));
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.