跳到正文
教程首页
FlutterCH 16ch16_bookmarks

ch16-bookmarks

综合项目(上):架构设计、数据层、依赖注入。完整工程共 116 个文件,其中 76 个文本源文件可在下面在线阅读。

76

在线文本文件

5,837

源码行数

dart / c / yaml

语言

301 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

textdartxmljsonkotlin

76 text files · 5,837 lines

darttest/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);
    });
  });
}

代码构成:text 77 KB · dart 69 KB · xml 41 KB · json 4 KB

本地运行

zip → 解压 → 执行
$cd examples/ch16-bookmarks && flutter run -d macos

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • flutter analyze 0 告警、flutter test 20 个用例全绿、debug 与 **release** 构建均真实启动成功
查看全部示例