Macro googletest::matchers::property
source · macro_rules! property { ($($t:tt)*) => { ... }; }
Expand description
Matches an object which, upon calling the given method on it with the given arguments, produces a value matched by the given inner matcher.
This is particularly useful as a nested matcher when the desired property cannot be accessed through a field and must instead be extracted through a method call. For example:
#[derive(Debug)]
pub struct MyStruct {
a_field: u32,
}
impl MyStruct {
pub fn get_a_field(&self) -> u32 { self.a_field }
}
let value = vec![MyStruct { a_field: 100 }];
verify_that!(value, contains(property!(MyStruct.get_a_field(), eq(100))))
Important: The method should be pure function with a deterministic output and no side effects. In particular, in the event of an assertion failure, it will be invoked a second time, with the assertion failure output reflecting the second invocation.
If the method returns a reference, then it must be preceded by a *
:
impl MyStruct {
pub fn get_a_field(&self) -> &u32 { &self.a_field }
}
verify_that!(value, contains(property!(*MyStruct.get_a_field(), eq(100))))
The method may also take additional arguments:
impl MyStruct {
pub fn add_to_a_field(&self, a: u32) -> u32 { self.a_field + a }
}
verify_that!(value, contains(property!(MyStruct.add_to_a_field(50), eq(150))))
Unfortunately, this matcher does not work with methods returning string slices:
#[derive(Debug)]
pub struct MyStruct {
a_string: String,
}
impl MyStruct {
pub fn get_a_string(&self) -> &str { &self.a_string }
}
let value = MyStruct { a_string: "A string".into() };
verify_that!(value, property!(*MyStruct.get_a_string(), eq("A string"))) // Does not compile
This macro is analogous to field
, except that it
extracts the datum to be matched from the given object by invoking a method
rather than accessing a field.
The list of arguments may optionally have a trailing comma.