Skip to content

Instantly share code, notes, and snippets.

@derekjw
Created May 6, 2016 15:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derekjw/0b3c0fcdfd237e64aecf1c62ef0fd9cf to your computer and use it in GitHub Desktop.
Save derekjw/0b3c0fcdfd237e64aecf1c62ef0fd9cf to your computer and use it in GitHub Desktop.
Rust unit test macro
macro_rules! unit_tests {
($( fn $name:ident($fixt:ident : $ftype:ty) $body:block )*) => (
$(
#[test]
fn $name() {
let mut $fixt = <$ftype as Fixture>::setup();
$body
$fixt.teardown();
}
)*
)
}
trait Fixture {
fn setup() -> Self;
fn teardown(self);
}
struct FooTestFixture<T> {
name: String,
num: T,
}
impl FooTestFixture<i32> {
fn add_some(&mut self) {
self.num += 10;
}
}
impl<T: Default> Fixture for FooTestFixture<T> {
fn setup() -> FooTestFixture<T> {
FooTestFixture {
name: String::from("Initialised"),
num: Default::default(),
}
}
fn teardown(mut self) {
self.name = "".to_string();
}
}
unit_tests!{
fn some_test_name(f: FooTestFixture<()>) {
assert_eq!(f.name, "Initialised");
f.name = "Foo".to_owned();
assert_eq!(f.name, "Foo");
}
fn another_test(g: FooTestFixture<i32>) {
assert_eq!(g.num, 0);
g.add_some();
assert_eq!(g.num, 10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment