Created
May 6, 2016 15:57
-
-
Save derekjw/0b3c0fcdfd237e64aecf1c62ef0fd9cf to your computer and use it in GitHub Desktop.
Rust unit test macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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