Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Модульные тесты

Rust и Cargo поставляются с простым фреймворком модульных тестов. Тесты помечаются #[test]. Модульные тесты часто помещают во вложенный модуль tests и используют #[cfg(test)], чтобы компилировать их только при сборке тестов.

// Copyright 2022 Google LLC
// SPDX-License-Identifier: Apache-2.0

fn first_word(text: &str) -> &str {
    match text.find(' ') {
        Some(idx) => &text[..idx],
        None => &text,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_empty() {
        assert_eq!(first_word(""), "");
    }

    #[test]
    fn test_single_word() {
        assert_eq!(first_word("Hello"), "Hello");
    }

    #[test]
    fn test_multiple_words() {
        assert_eq!(first_word(Привет, мир!), "Hello");
    }
}
  • Это позволяет модульно тестировать приватные вспомогательные функции.
  • Атрибут #[cfg(test)] активен только при запуске cargo test.