[][src]Crate default_test

Provides a Rust trait similar to Default that can be used in tests.

Often tests need to construct mock instances of structs. For example:

struct User {
    id: usize,
    name: String,
    email: String,
    admin: bool
}

While it's tempting to define Default, often tests need mock values for types that shouldn't apply in production code. Sometimes, tests need values for types that don't even implement Default.

This crate provides DefaultTest, a trait which can provide default instances with mock values. Tests can construct instances, and use the spread operator to override values.

use default_test::DefaultTest;

impl DefaultTest for User {
    fn default_test() -> Self {
        User {
            id: 0,
            name: "name".into(),
            email: "email".into(),
            admin: false
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test() {
        let user = User {
            id: 99
            ..User::test_default()
        };
        // ...
    }
}

This style makes tests much more stable, and when adding a field to a struct, it reduces the amount of required edits in your unit tests.

Roadmap:

  • Derive macro which fills sensible defaults that would be useful in unit test implementations.
    String files would be filled with their property name, and other types may use T::default() or unique values.

Traits

DefaultTest

A trait for giving a type a useful default value, in the scope of unit tests.