Модульные тесты
Атрибут test
«Модульные тесты» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Testing in Rust
Rust has built-in testing — no external framework needed. Tests are ordinary functions annotated with #[test], run by cargo test.
Your First Test
A test function takes no arguments and uses assertions. If it returns normally, it passes; if it panics, it fails.
fn add(a: i32, b: i32) -> i32 {
a + b
}
#[test]
fn it_adds() {
assert_eq!(add(2, 3), 5);
}
fn main() {
println!("{}", add(2, 3));
}Assertion Macros
The standard assertions are:
assert!(cond)— fails if condition is falseassert_eq!(a, b)— fails if not equalassert_ne!(a, b)— fails if equal
fn main() {
let x = 4;
assert!(x > 0);
assert_eq!(x, 4);
assert_ne!(x, 5);
println!("All assertions passed");
}The tests Module
By convention, unit tests live in a module annotated with #[cfg(test)] so they are compiled only during testing.
fn square(n: i32) -> i32 {
n * n
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn squares_correctly() {
assert_eq!(square(5), 25);
}
}
fn main() {
println!("{}", square(5));
}use super::*
Because the test module is nested, use super::* brings the parent module's items (the functions you want to test) into scope.
Running Tests
cargo test compiles and runs every test. It reports how many passed, failed, or were ignored.
cargo testTesting for Panics
Use #[should_panic] to assert that a function panics under certain conditions.
fn checked_div(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("division by zero");
}
a / b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "division by zero")]
fn panics_on_zero() {
checked_div(10, 0);
}
}
fn main() {}Tests Returning Result
A test can return Result, letting you use the ? operator. Returning Err fails the test.
fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse::<i32>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_number() -> Result<(), std::num::ParseIntError> {
let n = parse("42")?;
assert_eq!(n, 42);
Ok(())
}
}
fn main() {}Ignoring Tests
Mark slow or environment-specific tests with #[ignore]. Run them explicitly with cargo test -- --ignored.
#[test]
#[ignore]
fn expensive_test() {
// long-running work
}
fn main() {}Useful Test Flags
Helpful options when running tests:
cargo test name— run tests matching a namecargo test -- --nocapture— show println outputcargo test -- --test-threads=1— run serially
Testing Private Functions
Because the test module is nested inside the same file, it can reach private functions — something integration tests cannot do. This is a key advantage of unit tests.
fn internal(n: i32) -> i32 {
n + 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tests_private() {
assert_eq!(internal(4), 5);
}
}
fn main() {
println!("{}", internal(4));
}Quick Check
What attribute marks a function as a test that Cargo should run?
Recap
You learned Rust's built-in testing:
#[test]marks test functions- Assertions:
assert!,assert_eq!,assert_ne! - Tests live in a
#[cfg(test)]module withuse super::* #[should_panic]andResult-returning tests handle errorscargo testruns everything
Часто задаваемые вопросы
Урок «Модульные тесты» бесплатный?
Да — полный текст урока «Модульные тесты» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.
Чему я научусь в уроке «Модульные тесты»?
Атрибут test Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Learn Rust Coding?
Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Модульные тесты»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Learn Rust Coding?
Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.