Is there an elegant way to test Display formatting?

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?

Use five_pounds_fourteen_oz.to_string() to test :slightly_smiling_face:

3 Likes

Can’t believe I missed this…

Been there...

1 Like

Let's imagine it wasn't Display, but Debug or other formatting trait, then you can test it using the format! macro.

4 Likes

Maybe overkill in this case, but it might make sense to look into snapshot tests: I found insta to be very nice :slightly_smiling_face:

1 Like

Thanks so much!

In this case yes, it's a little overkill, but this is very cool! Thanks a lot for linking it. I'll keep it in mind for the future.