본문 바로가기
Rust

[Rust] Testing 예제 (26일차)

by 꾸압 2023. 1. 8.

 

<예제 코드_1>

pub fn add(left: usize, right: usize) -> usize {
    left + right
}

#[cfg(test)]
mod tests {
    #[test]
    fn exploration() {
        assert_eq!(2 + 2, 4);
    }
}

 


 

<예제 코드_2>

pub fn add(left: usize, right: usize) -> usize {
    left + right
}

#[cfg(test)]
mod tests {
    #[test]
    fn exploration() {
        assert_eq!(2 + 2, 4);
    }

    #[test]
    fn another() {
        panic!("Make this test fail");
    }
}

 


 

<예제 코드_3>

#[derive(Debug)]
pub struct Rectangle {
    length: u32,
    width: u32,
}

impl Rectangle {
    pub fn can_hold(&self, other: &Rectangle) -> bool {
        self.length > other.length && self.width > other.width
    }
}

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

    #[test]
    fn larger_can_hold_smaller() {
        let larger = Rectangle { length: 8, width: 7 };
        let smaller = Rectangle { length: 5, width: 1 };

        assert!(larger.can_hold(&smaller));
    }

    #[test]
    fn smaller_cannot_hold_larger() {
        let larger = Rectangle { length: 8, width: 7 };
        let smaller = Rectangle { length: 5, width: 1 };

        assert!(!smaller.can_hold(&larger));
    }
}

 


 

<예제 코드_4.1>

pub fn greeting(name: &str) -> String {
    format!("Hello {}!", name)
}

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

    #[test]
    fn greeting_contains_name() {
        let result = greeting("Carol");
        assert!(result.contains("Carol"));
    }
}

 


 

<예제 코드_4.2>

pub fn greeting(name: &str) -> String {
    String::from("Hello!")
}

#[test]
fn greeting_contains_name() {
    let result = greeting("Carol");
    assert!(
        result.contains("Carol"),
        "Greeting did not contain name, value was `{}`", result
    );
}

 


 

<참조 1> https://rinthel.github.io/rust-lang-book-ko/ch11-01-writing-tests.html

<참조 2>

 

 

'Rust' 카테고리의 다른 글

[Rust] Command Line Program 제작 (28일차)  (0) 2023.01.10
[Rust] Testing 예제_2 (27일차)  (0) 2023.01.09
[Rust] Lifetime 예제 (25일차)  (0) 2023.01.07
[Rust] Trait 예제 (24일차)  (0) 2023.01.06

댓글