Last active
September 18, 2023 13:05
-
-
Save easylive1989/5aec181220a7b2e9b8c1877a7aabe73c to your computer and use it in GitHub Desktop.
2023鐵人賽_D4_2
This file contains 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
import 'package:equatable/equatable.dart'; | |
class User extends Equatable { | |
final int id; | |
final String name; | |
const User({ | |
required this.id, | |
required this.name, | |
}); | |
factory User.fromJson(Map<String, dynamic> json) { | |
return User( | |
id: json['id'], | |
name: json['name'], | |
); | |
} | |
@override | |
List<Object?> get props => [id, name]; | |
} |
This file contains 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
import 'dart:convert'; | |
import 'package:http/http.dart'; | |
import 'user.dart'; | |
class UserRepository { | |
final Client client; | |
UserRepository() : this.create(Client()); | |
UserRepository.create(this.client); | |
Future<User> get(int userId) async { | |
var response = await client | |
.get(Uri.parse("https://jsonplaceholder.typicode.com/users/$userId")); | |
return User.fromJson(jsonDecode(response.body)); | |
} | |
} |
This file contains 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
import 'package:flutter_test/flutter_test.dart'; | |
import 'package:http/http.dart'; | |
import 'user.dart'; | |
import 'user_repository.dart'; | |
main() { | |
test("get user ok from api", () async { | |
var stubClient = StubClient(Response("{\"id\":1, \"name\": \"Tom\"}", 200)); | |
var userRepository = UserRepository.create(stubClient); | |
var user = await userRepository.get(1); | |
expect(user, const User(id: 1, name: "Tom")); | |
}); | |
} | |
class StubClient implements Client { | |
final Response response; | |
StubClient(this.response); | |
@override | |
Future<Response> get(Uri url, {Map<String, String>? headers}) async { | |
return response; | |
} | |
@override | |
dynamic noSuchMethod(Invocation invocation) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment