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:
```rust
#[test]
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 my codecov.io 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.
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.