CodeBlanks Logo Icon CodeBlanks

Summary - Testing

Combine unit, integration and doc tests to test a math crate.

Testing summary

Unit tests are written in src/ in a #[cfg(test)] mod tests module, also reaching private items. Integration tests in the tests/ folder use only the public API. Doc tests run the examples in /// comments. Checks: assert!, assert_eq!, assert_ne!; for an expected panic #[should_panic(expected = "..")]. Tests can also return Result<(), E>, so ? can be used.

Testing with ?

In tests whose setup steps may fail, ? is cleaner than chains of unwrap:

fn yas(s: &str) -> Result<u8, String> {
    s.trim().parse().map_err(|e| format!("geçersiz yaş: {e}"))
}

#[test]
fn yas_okunur() -> Result<(), String> {
    let y = yas(" 30 ")?;
    assert_eq!(y, 30);
    Ok(())
}

Practice Test returning Result

Write the yas function above and the yas_okunur test returning Result<(), String>. In main, print the result of yas(" 30 ") with {:?}.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn yas(s: &str) -> Result<u8, String> {
    s.trim().parse().map_err(|e| format!("geçersiz yaş: {e}"))
}

fn main() {
    println!("{:?}", yas(" 30 "));
}

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

    #[test]
    fn yas_okunur() -> Result<(), String> {
        let y = yas(" 30 ")?;
        assert_eq!(y, 30);
        Ok(())
    }
}

Expected output

Ok(30)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if a test returning <code>Result</code> returns <code>Err</code>?

  • The test counts as failed and the error is printed Correct answer
  • The test counts as passed
  • It doesn't compile
  • It's skipped

Explanation: #[should_panic] can't be used on tests returning Result; an expected error is written with assert!(r.is_err()).

2 Test return type

Question
#[test]
fn yas_okunur() -> ____ {
    let y = yas("30")?;
    assert_eq!(y, 30);
    Ok(())
}
Answer
#[test]
fn yas_okunur() -> Result<(), String> {
    let y = yas("30")?;
    assert_eq!(y, 30);
    Ok(())
}

Explanation: Tests returning Result can use ?.

3 Group summary

Term Meaning
#[test] Test function
tests/ folder Integration test
/// ``` Doc test
#[should_panic] Expected panic

All lessons in Intermediate