示例工程 ch03-types-collections
ch03-types-collections/test/types_test.dart
import 'package:ch03_types_collections/collections.dart';
import 'package:ch03_types_collections/generics.dart';
import 'package:ch03_types_collections/money.dart';
import 'package:ch03_types_collections/null_safety.dart';
import 'package:ch03_types_collections/shapes.dart';
import 'package:test/test.dart';
void main() {
group('值类型 Money', () {
test('按值相等,不是按引用', () {
const a = Money(2050);
final b = Money.fromYuan(20.5);
expect(a, b);
expect(identical(a, b), isFalse); // 两个不同对象
expect(a.hashCode, b.hashCode);
});
test('币种参与相等性与哈希', () {
expect(const Money(100) == const Money(100, currency: 'USD'), isFalse);
expect(const Money(100).hashCode == const Money(100, currency: 'USD').hashCode,
isFalse);
});
test('可以放进 Set / 当 Map 的 key', () {
const coffee = Money(100);
final set = <Money>{coffee, Money.fromYuan(1), const Money(200)};
expect(set.length, 2); // 两个 1.00 被去重
final m = <Money, String>{const Money(100): 'coffee'};
expect(m[Money.fromYuan(1)], 'coffee');
});
test('算术运算保持币种,混用币种抛 ArgumentError', () {
expect(const Money(100) + const Money(250), const Money(350));
expect(const Money(100) - const Money(250), const Money(-150));
expect(const Money(-150).isNegative, isTrue);
expect(() => const Money(100) + const Money(1, currency: 'USD'),
throwsArgumentError);
});
test('compareTo 与格式化', () {
expect(const Money(100).compareTo(const Money(250)), lessThan(0));
expect(const Money(2050).toString(), '20.50 CNY');
expect(const Money(5).yuan, 0.05);
});
});
group('增强枚举 Planet', () {
test('成员带字段与方法', () {
expect(Planet.values, hasLength(3));
expect(Planet.earth.radiusKm, 6371);
expect(Planet.earth.surfaceGravity, closeTo(9.82, 0.05));
expect(Planet.earth.label, 'earth (2/3)');
});
});
group('继承 / 接口 / sealed', () {
test('sealed 类的穷尽 switch', () {
expect(label(const Circle(1)), '圆形 r=1.0');
expect(label(const Rectangle(3, 4)), '矩形 3.0x4.0');
expect(label(const Rectangle.square(2)), '矩形 2.0x2.0');
expect(label(const Triangle(6, 5)), '三角形底 6.0 高 5.0');
});
test('多态求面积', () {
expect(totalArea(const <Shape2>[Rectangle(2, 3), Triangle(2, 3)]), 9.0);
expect(totalArea(const <Shape2>[]), 0.0);
});
test('equals / hashCode 用于去重', () {
expect(const Circle(1) == const Circle(1), isTrue);
final unit = Circle(1);
expect(<Shape2>{unit, Circle(1)}.length, 1);
});
test('extends + implements + super 调用', () {
const c = NamedCircle(2, '大圆');
expect(c.name, '大圆');
expect(c.describe(), '大圆: Circle(r=2.0)');
expect(
const NamedCircle(1, 'a').compareTo(const NamedCircle(2, 'b')),
lessThan(0),
);
expect(c, isA<Describable>());
expect(c, isA<Comparable<NamedCircle>>());
});
test('抽象类的具体方法可被继承', () {
const n = NamedCircle(1, 'x');
expect(n.area, closeTo(3.14159, 0.001));
});
});
group('泛型', () {
test('有界泛型用到 Comparable', () {
expect(maxOf(<int>[3, 1, 4, 1, 5]), 5);
expect(maxOf(<String>['pear', 'apple', 'zebra']), 'zebra');
expect(() => maxOf(<int>[]), throwsArgumentError);
});
test('泛型容器与 map', () {
expect(const Box<int>(2).map((int x) => x * 10), const Box<int>(20));
expect(const Box<int>(2).map((int x) => '$x'), const Box<String>('2'));
expect(const Box<int>(5).getOrElse(0), 5);
expect(const Pair<String, int>('a', 1).swapped.toString(), '(1: a)');
});
test('泛型在运行期是具化的', () {
expect(isIntList(<int>[1]), isTrue);
expect(isIntList(<String>['1']), isFalse);
});
test('sumOf 的 seed 参数', () {
expect(sumOf(<int>[1, 2, 3], seed: 0), 6);
expect(sumOf(<double>[1.5, 2.5], seed: 0.0), 4.0);
expect(sumOf(<int>[], seed: 42), 42);
});
test('协变写入在运行期被拦下', () {
final List<num> widened = widenToNum(<int>[1, 2]);
expect(widened, <num>[1, 2]);
// 静态检查通过(List<int> 是 List<num>),运行时炸——Dart 的泛型协变洞
expect(() => addDouble(widened), throwsA(isA<TypeError>()));
});
});
group('集合', () {
test('map/where/fold 链式', () {
expect(squaresOfEven(<int>[1, 2, 3, 4, 5, 6]), <int>[4, 16, 36]);
expect(squaresOfEven(<int>[]), isEmpty);
});
test('分组', () {
final grouped = groupByLength(<String>['go', 'dart', 'c', 'flutter']);
expect(grouped[2], <String>['go']);
expect(grouped[4], <String>['dart']);
expect(grouped[1], <String>['c']);
expect(grouped[7], <String>['flutter']);
});
test('词频统计', () {
expect(wordCounts('the quick the lazy dog the'),
<String, int>{'the': 3, 'quick': 1, 'lazy': 1, 'dog': 1});
expect(wordCounts(' '), isEmpty);
});
test('Set 去重保持插入顺序', () {
expect(uniqueWords('go go dart c'), <String>['go', 'dart', 'c']);
// toList 后顺序 = 首次出现顺序(Go 的 map 不保证)
expect(uniqueWords('bb aa bb').toList(), <String>['bb', 'aa']);
});
test('sort 原地修改,所以排序前要复制', () {
final original = <int>[3, 1, 2];
final sorted = sortedDescending(original);
expect(sorted, <int>[3, 2, 1]);
expect(original, <int>[3, 1, 2]); // 原列表未被改动
});
test('固定长度列表长度不可变,但元素可改', () {
final slots = fixedSlots();
expect(slots, hasLength(3));
slots[0] = 7;
expect(slots.first, 7);
expect(() => slots.add(1), throwsUnsupportedError);
});
test('List.unmodifiable 完全不可写', () {
expect(readOnlyTags(), contains('dart'));
expect(() => readOnlyTags().add('x'), throwsUnsupportedError);
});
test('collection-if / for / spread', () {
expect(buildTags(), <String>['dart']);
expect(buildTags(starred: true), <String>['dart', 'starred']);
expect(buildTags(extra: <String>['a']), <String>['dart', 'extra:a']);
expect(buildTags(more: <String>['b']), <String>['dart', 'b']);
});
test('嵌套 Map', () {
expect(inventory()['fruits']?['apple'], 3);
expect(inventory()['tools'], <String, int>{'hammer': 1});
});
});
group('null 安全', () {
test('可空参数 + 非空返回', () {
expect(displayName(null), 'anonymous');
expect(displayName(' '), 'anonymous');
expect(displayName(' Ada '), 'Ada');
});
test('类型提升让 ! 变得多余', () {
expect(shout(null), '...');
expect(shout('hi'), 'HI');
});
test('?? 与可空返回', () {
expect(configOrDefault(<String, String>{'k': 'v'}, 'k'), 'v');
expect(configOrDefault(<String, String>{}, 'k'), 'default');
expect(firstWord(' '), isNull);
expect(firstWord('hello world'), 'hello');
});
test('嵌套 map 的安全导航', () {
expect(
cityOfUser(<String, Object?>{
'address': <String, Object?>{'city': '上海'},
}),
'上海',
);
expect(cityOfUser(null), '未知');
expect(cityOfUser(<String, Object?>{'address': 'not-a-map'}), '未知');
expect(cityOfUser(<String, Object?>{'address': <String, Object?>{}}), '未知');
});
test('late final 延迟初始化且只算一次', () {
final cfg = LazyConfig();
expect(cfg.computeCount, 0); // 还没读过
expect(cfg.dbPath, '/tmp/ch03-app.db');
expect(cfg.computeCount, 1);
expect(cfg.dbPath, '/tmp/ch03-app.db');
expect(cfg.computeCount, 1); // 只算了一次
});
test('late 未初始化与 ! 强制解包的运行期错误', () {
expect(uninitializedLate, throwsA(predicate(
(Object e) => e.toString().contains('LateInitializationError'))));
expect(() => unsafeBang(null), throwsA(isA<TypeError>()));
});
test('集合越界访问返回 null 而非垃圾内存', () {
expect(firstOrNull(<int>[]), isNull);
expect(firstOrNull(<int>[9]), 9);
expect(lookup(<String, int>{'a': 1}, 'b'), isNull);
expect(lookup(<String, int>{'a': 1}, 'a'), 1);
});
});
}