liveBook · Manning

Property-based testing

As explained in Code Like a Pro in Rust

Property-based testing is a software-testing technique that generates many inputs to check whether general properties hold.

Property-based testing generates random inputs and checks whether general properties hold, reducing unit-test maintenance while increasing assurance. section 6.10 section 6.3

Use it with these practical constraints:

  • Use proptest to generate test data, verify results, and report the minimum input that reproduces an error. section 6.3
  • Keep tests for well-known values when checking specification compliance; generated cases are not a complete replacement. section 6.3
  • Tune the number of generated cases because broader random testing can consume more CPU without covering every possible outcome. section 6.3
  • Watch arithmetic semantics: debug-mode Rust tests use checked arithmetic, so generated integer inputs can expose overflow. section 6.3

Finding an overflowing adder

A proptest test compares a generic adder with ordinary addition over generated i64 values. The test finds overflow and reports a minimal failing pair; changing the implementation and oracle to wrapping addition makes the test pass. section 6.3

Listing 6.3 Code listing of adder with proptest
pub fn add<T: std::ops::Add<Output = T>>(a: T, b: T) -> T {
    a + b
}
 
#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;                 #1
    proptest! {
        #[test]
        fn test_add(a: i64, b: i64) {         #2
            assert_eq!(add(a, b), a + b);     #3
        }
    }
}

Inspect the focused Rust implementation using the proptest macro, generated i64 arguments, and an equality property. section 6.3

How Code Like a Pro in Rust covers it

How deep it goes
Explains proptest usage, minimal failing cases, CPU tradeoffs, and overflow behavior; stops short of exhaustive input coverage.
Examples
Uses a generic Rust adder to expose signed-integer overflow and demonstrate wrapping arithmetic.
What you can do after
Apply it via proptest to generate inputs, verify properties, and isolate minimal failing cases.
How it connects
Connects unit testing with proptest, QuickCheck, assertions, and code coverage.

Also explained in

Compare how 8 books explain property-based testing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.