DEV Community

Pallat Anchaleechamaikorn
Pallat Anchaleechamaikorn

Posted on

3 1

เขียน unit test ใน Rust

การเขียน unit test ในภาษา Rust โดยปกติแล้วจะเขียนลงไปใน file เดียวกันกับ code ที่ใช้งานจริงเลย แต่ถ้าเป็น integration test จะแยกไปเขียนใน /tests ที่วางไว้ระดับเดียวกับ /src

วิธีเขียน unit test ทำแบบนี้

fn add(a:i32, b:i32) -> i32 {a+b}

fn main() {
    println!("{}",add(1,2));
}

#[cfg(test)]
mod tests {
    #[test]
    fn add_correct() {
        assert_eq!(3, super::add(1,2));
    }
}

Enter fullscreen mode Exit fullscreen mode

จากตัวอย่าง อธิบายได้ว่า เรามี function add ไว้บวกเลขธรรมดา ทีนี้เวลาเราเขียน unit test ลงไปใน code ตรงๆ เวลา compile มันก็จะติดส่วนที่เป็น unit test เข้าไปด้วย และเพื่อป้องกันเหตุนั้น เราจึงใส่

#[cfg(test)] ไว้บน mod tests เพื่อบอก compiler ว่าส่วนต่อไปนี้เป็น unit test ไม่ต้องเอาไป compile

จากนั้นก็สร้าง module ชื่อ tests ลงไปเลย และในทุกๆ function ที่เป็น unit test ให้ใส่ #[test] ไว้

จากนั้นเวลาจะไปเรียก function จริงๆ จะต้องเรียกผ่าน super:: และถ้าขี้เกียจ ก็อาจจะใช้ use super::*; ช่วยได้ เช่น

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

    #[test]
    fn add_correct() {
        assert_eq!(3, add(1,2));
    }
}
Enter fullscreen mode Exit fullscreen mode

เวลารันเทส ใช้คำสั่ง

cargo test

เพียงเท่านี้ก็เริ่มเขียน unit test ใน Rust กันได้แล้ว

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs