How to Write Tests

In this chapter, we'll explore learn the basics of writing tests in mana.

How to Write Tests

Tests are Mana functions that verify non-test code is functioning correctly. Test functions typically:

  1. Set up needed data or state
  2. Run the code you want to test
  3. Assert the results are what you expect

The #[test] Attribute

The #[test] attribute marks a function as a test:

#[test]
fn exploration() -> void {
    assert_eq(2 + 2, 4)
}

Checking Results with assert

Use assert for boolean conditions:

#[test]
fn larger_can_hold_smaller() -> void {
    let larger = Rectangle { width: 8, height: 7 }
    let smaller = Rectangle { width: 5, height: 1 }
 
    assert(larger.can_hold(smaller))
}

Testing Equality with assert_eq

fn add_two(a: int) -> int {
    return a + 2
}
 
#[test]
fn it_adds_two() -> void {
    assert_eq(4, add_two(2))
}

When assertions fail, they show both values:

assertion failed: `(left == right)`
  left: `4`
  right: `5`

Testing Inequality with assert_ne

#[test]
fn not_equal() -> void {
    assert_ne(add_two(2), 5)
}

Custom Failure Messages

#[test]
fn greeting_contains_name() -> void {
    let result = greeting("Carol")
    assert(
        result.contains("Carol"),
        "Greeting did not contain name, got: ", result
    )
}

Testing for Panics

Use #[should_panic] for code that should panic:

struct Guess {
    value: int
}
 
impl Guess {
    fn new(value: int) -> Guess {
        if value < 1 || value > 100 {
            panic("Guess must be between 1 and 100")
        }
        return Guess { value }
    }
}
 
#[test]
#[should_panic]
fn greater_than_100() -> void {
    Guess::new(200)
}

Add expected message for specificity:

#[test]
#[should_panic(expected = "between 1 and 100")]
fn greater_than_100() -> void {
    Guess::new(200)
}

Using Result in Tests

Return Result for tests that shouldn't panic:

#[test]
fn it_works() -> Result<(), string> {
    if 2 + 2 == 4 {
        return Ok(())
    } else {
        return Err("two plus two does not equal four")
    }
}

Continue to Controlling How Tests Are Run.