Hello,
I am writing an implementation for fmt::Display
for one of my structs. I have an idea of how the formatted output should look, and so I'm trying to write unit tests to ensure the behaviour is correct. For instance:
impl fmt::Display for MassMeasure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.unit {
MassUnit::Kilogram => write!(
f,
"{:.2}kg",
self.scalar
),
MassUnit::Pound => {
let scalar = self.scalar;
if (scalar - scalar.round()).abs() >= 1.0/32.0 {
write!(
f,
"{}lb {}oz",
scalar.round(),
((scalar - scalar.floor())*16.0).round()
)
} else {
write!(
f,
"{}lb",
scalar.round()
)
}
},
// ...
}
}
}
…and now I'd like to test that the format is correct given sample MassMeasure
structs, for instance one with
MassMeasure{ scalar: 5.875, unit: MassUnit::Pound }
should format to "5lb 14oz
"
#[test]
fn test_lb_oz_format() {
let five_pounds_fourteen_oz = MassMeasure{
scalar: 5.875,
unit: MassUnit::Pound
};
assert_eq!("5lb 14oz", /* ...something? */);
}
How can I test that my Display
implementation is correct?