Rust
自动化测试
测试三步骤
- 准备数据状态(Arrange)
- 运行测试代码(Act)
- 断言结果(Assert)
#[test] 属性
- 使用
#[test]标注的函数变为测试函数 - 用
cargo test运行所有测试 - 每个测试函数独立运行,在单独的线程中执行
- 一旦发生 panic,该测试即失败
- 创建 library(
cargo new --lib)会自动生成mod tests,里面预置一个测试函数
#[test]
fn test_addition() {
let sum = 2 + 2;
assert_eq!(sum, 4);
}
断言宏(assert)
| 宏 | 行为 | 使用场景 |
|---|---|---|
assert! | 表达式为 true 通过,false 失败 | 判断布尔条件 |
assert_eq! | 使用 == 比较,相等通过 | 判断两值相等 |
assert_ne! | 使用 != 比较,不相等通过 | 判断两值不相等 |
#[test]
fn test_assert() {
assert!(1 < 2); // true -> 通过
assert_eq!(2 + 2, 4); // == -> 通过
assert_eq!(2 + 2, 5); // ✗ 失败,打印: left: 4, right: 5
assert_ne!(1, 2); // != -> 通过
}
自定义错误信息
- 失败时自定义信息会与标准失败信息一起打印
- 格式为:
assert!(条件, "自定义信息")
#[test]
fn test_with_message() {
let name = String::from("Alice");
assert!(
name.len() > 10,
"名字长度应大于 10,实际长度为 {}",
name.len()
);
// 失败时输出:
// panic: 名字长度应大于 10,实际长度为 5
// left: false, right: true
}
测试组织:#[cfg(test)] 模块
- 用
#[cfg(test)]标注的模块只在测试编译时生效,不会进入生产构建 - 子模块通过
use super::*访问父模块(包括私有函数)
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
fn private_helper() -> i32 { // 私有函数也能测
42
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add() {
assert_eq!(add(1, 2), 3);
}
#[test]
fn test_private() {
assert_eq!(private_helper(), 42);
}
}
测试返回 Result
- 测试函数支持返回
Result<(), E>,用?简化错误处理 - 返回
Err时测试失败
#[test]
fn test_result() -> Result<(), String> {
let result = "42".parse::<i32>().map_err(|e| e.to_string())?;
assert_eq!(result, 42);
Ok(())
}
cargo test 常用参数
cargo test # 运行所有测试
cargo test 名称关键词 # 只运行名称含关键词的测试
cargo test -- --nocapture # 显示测试中的 println! 输出
cargo test -- --ignored # 运行被忽略的测试
cargo test --test 文件名 # 运行指定集成测试文件
其他常用注解
#[test]
#[should_panic(expected = "除以零")] // 预期 panic,无 panic 反而失败
fn test_panic() { /* ... */ }
#[test]
#[ignore = "需要数据库,太慢"] // 默认跳过,不参与 cargo test
fn test_slow() { /* ... */ }
测试分类
| 类型 | 位置 | 测试对象 | 特点 |
|---|---|---|---|
| 单元测试 | src/ 内 mod tests | 模块内部函数(含私有) | 速度快,测试私有逻辑 |
| 集成测试 | tests/ 目录下独立文件 | 公共 API,外部调用视角 | 每个文件是一个独立 crate |
| 文档测试 | 代码注释 /// 中代码块 | 文档中的示例代码 | cargo test 自动运行 |
集成测试(tests/ 目录)
- 创建
tests/目录,里面的每个.rs文件都是一个独立的 crate - 只能访问 crate 的公共 API(
pub),不能访问私有函数 tests/common/mod.rs可放共享辅助代码(mod.rs命名时不会被视为测试文件)
// tests/integration_test.rs
use my_lib::add; // 需要引入库 crate
#[test]
fn test_add_integration() {
assert_eq!(add(1, 2), 3);
}
// tests/common/mod.rs —— 共享辅助函数
pub fn setup() -> String {
String::from("test environment ready")
}
// tests/another_test.rs —— 使用公共辅助
mod common;
#[test]
fn test_with_setup() {
let env = common::setup();
assert!(env.contains("ready"));
}
文档测试(Doctest)
- 写在
///文档注释的代码块中 - 目的:示例代码正确且可运行
cargo test会编译并运行这些代码块
/// 两数相加示例
///
/// ```
/// let result = my_lib::add(1, 2);
/// assert_eq!(result, 3);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
测试输出格式
running 3 tests
test test_add ... ok
test test_private ... ok
test test_panic ... FAILED
failures:
---- test_panic stdout ----
thread 'test_panic' panicked at src/lib.rs:10:5
note: run with `RUST_BACKTRACE=1` for a backtrace.
failures:
test_panic
test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
断言要求:Debug trait
assert_eq!/assert_ne!失败时需要打印左右值- 参与比较的类型必须实现
Debugtrait(几乎所有标准类型都实现了) - 自定义类型可
#[derive(Debug)]
#[derive(Debug, PartialEq)]
struct Point { x: i32, y: i32 }
#[test]
fn test_point() {
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 1, y: 2 };
assert_eq!(p1, p2); // 需要 PartialEq;失败时打印需要 Debug
}
浮点数断言技巧
- 浮点数直接用
==有精度问题,不可靠 - 使用近似比较:
(a - b).abs() < 1e-9,或自制断言
#[test]
fn test_float() {
let a = 0.1 + 0.2;
let b = 0.3;
assert!((a - b).abs() < 1e-9, "浮点数应近似相等");
}
并发与单线程执行
- 测试默认多线程并行运行(加快速度)
- 但并行时各测试共享状态会产生竞争问题,需用
--test-threads
cargo test -- --test-threads=1 # 单线程串行执行
cargo test -- --test-threads=4 # 指定 4 个线程
cargo test -- --test-threads=1 --nocapture # 串行且打印输出
Cargo.toml 测试配置
[profile.test]
opt-level = 0 # 测试编译优化级别(0 更快编译)
debug = true # 保留调试符号
测试命名与组织习惯
- 测试函数命名常用
test_前缀,或用when_/should_描述行为 - 通过
super::*引入被测模块 - 用
#[cfg(test)]确保测试代码不进入生产构建
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn when_input_zero_should_not_panic() {
// ...
}
#[test]
fn should_return_empty_string() {
// ...
}
}
JS
var/let/const 区别与块级作用域
作用域对比
| 关键字 | 作用域 | 重复声明 | 变量提升 | 暂时性死区 | 重新赋值 |
|---|---|---|---|---|---|
var | 函数级 | ✅ | ✅ 值为 undefined | ❌ 无 | ✅ |
let | 块级 | ❌ | ✅ 但不可访问 | ✅ 有 | ✅ |
const | 块级 | ❌ | ✅ 但不可访问 | ✅ 有 | ❌ |
核心要点
var不受{}限制,会泄漏到函数作用域let/const只在块级作用域({})内有效const是引用不可变,对象/数组内部属性仍可修改
// var 无块级作用域
if (true) {
var a = 1;
}
console.log(a); // 1
// let 有块级作用域
if (true) {
let b = 2;
}
console.log(b); // ❌ ReferenceError
// const 不可重新赋值
const PI = 3.14;
PI = 3.15; // ❌ TypeError
// const 对象内部可变
const obj = { name: "Alice" };
obj.name = "Bob"; // ✅ 允许
obj = {}; // ❌ 不允许
经典循环闭包问题
// var:全部输出 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 3 3 3
// let:输出 0 1 2(每次迭代独立块级作用域)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// 0 1 2
使用建议
- 默认用
const - 需要重新赋值时用
let - 现代代码中避免使用
var
基本类型(string、number、boolean、null、undefined、symbol、bigint)与引用类型
基本类型(值类型)
- 存储在栈内存中,按值访问
- 7 种:
string、number、boolean、null、undefined、symbol、bigint
let a = 10;
let b = a; // b = 10,是副本
b = 20;
console.log(a); // 10(互不影响)
引用类型(对象类型)
- 存储在堆内存中,变量存的是内存地址
- 包括:
Object、Array、Function、Date、RegExp等
let obj1 = { name: "Alice" };
let obj2 = obj1; // 指向同一个对象
obj2.name = "Bob";
console.log(obj1.name); // 'Bob'(互相影响)
// 值比较 vs 引用比较
console.log({} === {}); // false(不同引用)
console.log([] === []); // false
console.log({} == {}); // false
类型检测
typeof 42; // 'number'
typeof "hello"; // 'string'
typeof true; // 'boolean'
typeof undefined; // 'undefined'
typeof null; // 'object' ⚠️ 历史遗留 bug
typeof Symbol(); // 'symbol'
typeof 10n; // 'bigint'
typeof {}; // 'object'
typeof []; // 'object'
typeof function () {}; // 'function'
null的typeof是'object',这是 JavaScript 的历史遗留 bug,需要用=== null判断。
类型转换、== 与 === 区别
显式类型转换
// 转字符串
String(123); // '123'
(123).toString(); // '123'
// 转数字
Number("42"); // 42
Number("abc"); // NaN
parseInt("42px"); // 42
+"42"; // 42
// 转布尔
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
Boolean([]); // true
隐式类型转换(== 自动转换)
== 会先做类型转换再比较;=== 要求类型和值都相同。
| 表达式 | == | === |
|---|---|---|
1 == '1' | ✅ true(转换后相等) | ❌ false(类型不同) |
0 == false | ✅ true | ❌ false |
'' == false | ✅ true | ❌ false |
null == undefined | ✅ true | ❌ false |
[] == '' | ✅ true | ❌ false |
null == 0 | ❌ false | ❌ false |
比较规则
// == 的转换规则
"1" == 1; // true(字符串转数字)
true == 1; // true(布尔转数字)
null == undefined; // true(特殊规则)
// === 严格比较(推荐使用)
"1" === 1; // false
true === 1; // false
null === undefined; // false
注意事项
- 推荐始终使用
===(或!==),避免隐式转换带来的坑 - 判断
NaN不能用==/===,要用Number.isNaN()
NaN === NaN; // false(NaN 不等于任何值)
Number.isNaN(NaN); // true ✅
Number.isNaN("abc"); // false(不会先转类型)
类型转换面试重点
// 有趣的空值比较
[] == false; // true([] → '' → 0,false → 0)
[] == []; // false(不同引用)
![] == []; // true(![] → false → 0,[] → 0)
// 字符串与数字比较时,字符串会转数字
"5" > 3; // true
"abc" > 3; // false(NaN)
