示例工程 ch16-bookmarks
ch16-bookmarks/test/repository_test.dart
import 'dart:convert';
import 'dart:io';
import 'package:ch16_bookmarks/src/core/config.dart';
import 'package:ch16_bookmarks/src/data/database.dart';
import 'package:ch16_bookmarks/src/data/drift_bookmark_repository.dart';
import 'package:ch16_bookmarks/src/data/remote_api.dart';
import 'package:ch16_bookmarks/src/domain/bookmark.dart';
import 'package:ch16_bookmarks/src/domain/bookmark_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
/// 假远程 API:可控的返回/异常。
class FakeRemoteApi implements BookmarkRemoteApi {
FakeRemoteApi({this.drafts = const <BookmarkDraft>[], this.error});
final List<BookmarkDraft> drafts;
final Object? error;
var calls = 0;
@override
Future<List<BookmarkDraft>> fetchDrafts({int limit = 10}) async {
calls++;
if (error != null) throw error!;
return drafts.take(limit).toList(growable: false);
}
}
const List<BookmarkDraft> sampleDrafts = <BookmarkDraft>[
BookmarkDraft(title: 'Dart 官网', url: 'https://dart.dev', note: '语言文档'),
BookmarkDraft(title: 'Flutter 官网', url: 'https://flutter.dev', note: '框架文档'),
];
void main() {
group('远程 API(http)', () {
const AppConfig config = AppConfig(baseUrl: 'https://example.test');
test('把 /posts 映射成草稿', () async {
final MockClient client = MockClient((http.Request request) async {
expect(request.url.path, '/posts');
expect(request.url.queryParameters['_limit'], '2');
return http.Response(
jsonEncode(<Map<String, Object?>>[
<String, Object?>{'id': 1, 'title': ' hello ', 'body': 'world'},
<String, Object?>{'id': 2, 'title': 'again', 'body': 'body'},
]),
200,
);
});
final List<BookmarkDraft> drafts =
await HttpBookmarkRemoteApi(client: client, config: config).fetchDrafts(limit: 2);
expect(drafts, hasLength(2));
expect(drafts.first.title, 'hello'); // 已 trim
expect(drafts.first.url, 'https://jsonplaceholder.typicode.com/posts/1');
expect(drafts.first.note, 'world');
});
test('非 2xx → SyncException', () async {
final MockClient client = MockClient((http.Request request) async => http.Response('boom', 503));
await expectLater(
HttpBookmarkRemoteApi(client: client, config: config).fetchDrafts(),
throwsA(isA<SyncException>().having((SyncException e) => e.message, 'message', contains('503'))),
);
});
test('非法 JSON → SyncException', () async {
final MockClient client = MockClient((http.Request request) async => http.Response('<html>', 200));
await expectLater(
HttpBookmarkRemoteApi(client: client, config: config).fetchDrafts(),
throwsA(isA<SyncException>()),
);
});
test('连不上 → SyncException', () async {
final MockClient client = MockClient((http.Request request) async {
throw const SocketException('no route');
});
await expectLater(
HttpBookmarkRemoteApi(client: client, config: config).fetchDrafts(),
throwsA(isA<SyncException>()),
);
});
});
group('仓储(drift 内存库)', () {
late AppDatabase db;
setUp(() => db = AppDatabase.memory());
tearDown(() => db.close());
test('增删查 + 响应式 watch', () async {
final DriftBookmarkRepository repo = DriftBookmarkRepository(db, FakeRemoteApi());
final List<List<Bookmark>> emissions = <List<Bookmark>>[];
final subscription = repo.watchAll().listen(emissions.add);
addTearDown(subscription.cancel);
await Future<void>.delayed(const Duration(milliseconds: 20));
final int id = await repo.add(const BookmarkDraft(title: 'A', url: 'https://a.test'));
await Future<void>.delayed(const Duration(milliseconds: 20));
expect(emissions.first, isEmpty);
expect(emissions.last.single.id, id);
expect(emissions.last.single.title, 'A');
await repo.setFavorite(id, favorite: true);
await Future<void>.delayed(const Duration(milliseconds: 20));
expect(emissions.last.single.favorite, isTrue);
await repo.delete(id);
await Future<void>.delayed(const Duration(milliseconds: 20));
expect(emissions.last, isEmpty);
});
test('同一 url 不重复插入', () async {
final DriftBookmarkRepository repo = DriftBookmarkRepository(db, FakeRemoteApi());
final int a = await repo.add(const BookmarkDraft(title: 'A', url: 'https://a.test'));
final int b = await repo.add(const BookmarkDraft(title: 'A again', url: 'https://a.test'));
expect(b, a);
expect(await db.watchAllRows().first, hasLength(1));
});
test('importFromRemote 统计新增数,重复导入为 0', () async {
final FakeRemoteApi remote = FakeRemoteApi(drafts: sampleDrafts);
final DriftBookmarkRepository repo = DriftBookmarkRepository(db, remote);
expect(await repo.importFromRemote(), 2);
expect(remote.calls, 1);
expect(await db.watchAllRows().first, hasLength(2));
// 第二次导入:url 已存在 → 新增 0
expect(await repo.importFromRemote(), 0);
expect(await db.watchAllRows().first, hasLength(2));
});
test('远程失败时不写库', () async {
final DriftBookmarkRepository repo = DriftBookmarkRepository(
db,
FakeRemoteApi(error: const SyncException('断网了')),
);
await expectLater(repo.importFromRemote(), throwsA(isA<SyncException>()));
expect(await db.watchAllRows().first, isEmpty);
});
test('收藏项排在前面', () async {
final DriftBookmarkRepository repo = DriftBookmarkRepository(db, FakeRemoteApi());
final int a = await repo.add(const BookmarkDraft(title: 'A', url: 'https://a.test'));
await repo.add(const BookmarkDraft(title: 'B', url: 'https://b.test'));
await repo.setFavorite(a, favorite: true);
final List<Bookmark> list = await repo.watchAll().first;
expect(list.first.id, a);
expect(list.first.favorite, isTrue);
});
});
group('草稿校验', () {
test('标题与链接规则', () {
expect(const BookmarkDraft(title: '', url: 'https://a.test').validate(), contains('标题'));
expect(const BookmarkDraft(title: 'x', url: 'not a url').validate(), contains('链接'));
expect(const BookmarkDraft(title: 'x', url: 'ftp://a.test').validate(), contains('链接'));
expect(const BookmarkDraft(title: 'x', url: 'https://a.test').validate(), isNull);
});
});
}