Rust

Lesson 10

Tests, fixtures, and assertions

Build small fixtures and assert domain outcomes instead of only checking that code does not panic.

Good Code

tests/review_rules.rs
#[test]
fn rejects_empty_review_title() {
    // The fixture names the invalid input the rule must reject.
    let review = ReviewDraft {
        title: String::from("   "),
        body: String::from("Useful notes"),
    };

    let error = validate_review(&review).unwrap_err();

    assert_eq!(error.field(), "title");
}

Bad Code

tests/review_rules.rs
#[test]
fn validates_review() {
    let review = ReviewDraft::default();

    // This assertion only proves the function returned some success value.
    assert!(validate_review(&review).is_ok());
}

Review Notes

What to review

Good Code

The good version builds the invalid input directly and asserts the field reported by the validator. A future regression in title validation will fail the test.

Bad Code

The bad version uses a default fixture and checks only a success path. The test name and assertion do not protect a specific rule.

Takeaways

  • A Rust test should name the input fixture and assert the observable result that protects the review rule.