fmt::Formatter<'a> new?


For my project I would like to get a high code unit test coverage. I tried to use grcov, but for fmt::Debug and fmt::Display implementation, it does not count my unit tests. I would like to write unit tests directly testing the fmt::Display -> fmt() and fmt::Debug -> fmt() functions, but there functions need an fmt::Formatter<'a> as input. I tried to figure it out how to get a new instant of it but till now, without any success.

Could you help me? How to get an fmt::Formatter<'a> or how to test properly my Display and Debug implementations.

My Display implementation:

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::InternalError(msg) => write!(f, "Internal error: {}", msg),

and my unit test looks like this:

    fn test_display() {
        let err = Error::InternalError("test error".into());
        assert_eq!(format!("{}", err), "Internal error: test error");

With this test I can effectively test my Display implementation, however the test coverage says the implementation is not covered by a unit test. My guess is as I do not call the fmt() method directly, it cannot connect them.

Here is the file where I encounter this issue:

Thank you in advance.
Best wishes,
Peter Mezei.

1 Like

Here is my profile about the related file, showing that the implementations are not covered by tests - but the unit tests are displayed below.

It looks like Formatter doesn't have a (public) constructor, so you can't create one directly. However, if you use the format!() macro, or .to_string(), their implementation will create one and pass it in.

Yep, but how i can use it to test fn fmt(&self, f: &mut fmt::Formatter<'_>)?

my_stuff.to_string() == "the string I expect"?

1 Like

And format!("{:?}", my_stuff) instead of my_stuff.to_string() to test the Debug impl.


Thank you for your help. I know how to use Display and Debug traits, but looking on my code coverage results - using kcov -, it did seem like i need to call the trait methods directly in my unit tests, so using format!("{}", variable") is not count in tests as it calls the fmt method in the background, so somehow calling variable.fmt(...) directly.
Anyway I changed kcov to tarpaulin and it solved my issue.
Thank you again.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.