测试公开契约
Coddy 面向 C 开发者的 Dart 课程的第 41 课,共 48 课。
如果定义了 NDEBUG,来自 assert.h 的 C assert 就会编译为空操作,许多发布版本都是如此;除非启用 Dart 断言,否则它们同样会被关闭。必需的行为探测会使用显式检查:在 C 中使用 if 报告并退出,在 Dart 中使用 throw。边界测试可以区分看似合理但错误的实现,而不依赖私有字段。C 字符串是字节序列,因此 U+0080 对应 UTF-8 字节对 0xC2 0x80,而 Dart 的 codeUnits 是 UTF-16 单元。
必需的探测会使用显式抛出,因为 Dart 断言可能被禁用。测试公开行为和边界,而不是检查源代码字符串或私有实现细节。这里展示的 ASCII 检查并未实现 Store 任务。
完整的 C 程序:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static void check(bool ok) {
if (!ok) {
fprintf(stderr, "failed\n");
exit(1);
}
}
static bool ascii(const char *s) {
for (; *s; s++)
if ((unsigned char)*s >= 128) return false;
return true;
}
int main(void) {
check(ascii(""));
check(ascii("v2"));
check(ascii("\x7f"));
check(!ascii("\xc2\x80"));
printf("checks passed\n");
return 0;
}
完整的 Dart 程序:
void check(bool ok){if(!ok)throw StateError('failed');}
bool ascii(String s)=>s.codeUnits.every((u)=>u<128);
void main(){check(ascii(''));check(ascii('v2'));check(ascii('\u007f'));check(!ascii('\u0080'));print('checks passed');}挑战
简单实现 Store(int limit),并提供 bool put(String key,int value)、int? get(String key) 和 getter size。只有在容量未满时才能插入新键;即使容量已满,替换现有键也应成功。拒绝操作时,内容保持不变。输入为容量,后接完整的 key value 键值对;输出为 accepted|size。容量范围为 0 到 100,值为整数。独立探测还会检查已存储的值和拒绝行为。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立探测公共 API,并在结果后打印一个换行符。
你的代码写在 Store.dart、exercise.dart 中。main.dart 包含提供的输入/输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Store.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final s=Store(1);check(s.put('a',2));check(!s.put('b',3)&&s.get('b')==null);check(s.put('a',7)&&s.get('a')==7&&s.size==1);check(!Store(0).put('x',1));
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Dart中的所有课
自己练习: Dart 在线编译器