Introduction
An important part of development is writing tests. When I started, things like unit tests didn’t even exist. Now, I can’t imagine doing development without them.
I’m a strong believer in test-driven development (TDD). While I don’t strictly adhere to writing tests before implementation, I’ve learned that tests are not just about ensuring quality—they’re also powerful development tools.
I often use tests along with breakpoints to step through code. This approach helps me implement small parts at a time, using tests and the debugger to verify my progress during development.
One of the things I love about Rust is that the documentation and tests are side by side with the code.
Checking the coverage
I’ve written a bunch of tests to help develop a feature. The feature works, and all the tests pass, but am I testing everything? This is where code coverage comes in. By running code coverage, I can gauge how much of my code is being tested. While aiming for 100% coverage is ideal, it’s often impractical. The last 5% of coverage usually requires more effort than the initial 95%. A cost-benefit analysis is necessary to determine what constitutes good coverage. I like 100%, but it’s not always achievable.
To get coverage working in my Rust project, I installed and used cargo-llvm-cov
. The installation was straightforward, and all I needed to do was run the tests.
After running the tests with cargo test
, generating the code coverage report is as simple as running cargo llvm-cov
. This provides a quick overview of test coverage.
For a more in-depth view, you can generate an HTML report. Running cargo llvm-cov --html
creates an HTML report at target/llvm-cov/html/index.html
. This allows you to view the coverage and see a highlighted report within your source files.
HTML code coverage report
In this picture, you can see all the source files and their coverage. The api_builder
is a temporary experiment, so I didn’t bother writing tests for it since I plan to delete it. The switch
is a work in progress and requires more testing.
You can click on the file name links on the left to view the source code and its summary.
Source code overview
The values on the left, 1 and 0 indicates how many times was that line of code executed during the tests. In this case most of then where 1 and the error was never tested.
Since passing and failing tests are important, this might be something I want to look at 🙂
Conclusion
The performance is fantastic—this small project took less than a second to run the tests and generate the report. The information is concise and provides a quick overview of where more work is needed.
Honestly, these are the kinds of tools you can’t live without.