pub trait DefaultTest {
// Required method
fn default_test() -> Self;
}
Expand description
A trait for giving a type a useful default value, in the scope of unit tests.
Sometimes, unit tests need to construct a mock value when working with structs, such as:
struct User {
id: usize,
name: String,
email: String,
admin: bool
}
DefaultTest can be used to define default mocked values for use in tests. 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()
};
// ...
}
}
Required Methods§
Sourcefn default_test() -> Self
fn default_test() -> Self
Returns a “default value” for a type, containing mocked values suitable for use in tests. Default values may contain literals, unique numbers, etc, to make test assertions easier to work with.
§Examples
use default_test::DefaultTest;
let x: String = DefaultTest::default_test();
Make your own:
use default_test::DefaultTest;
struct Foo {
bar: String
}
impl DefaultTest for Foo {
fn default_test() -> Self {
Self {
bar: "bar".into()
}
}
}
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.