Visualizing Rust Code Coverage in VS Code
Hello Rustaceans! I am currently learning Rust and practicing writing unit tests with my favorite code editor, Visual Studio Code. When I write code in Go, it feels great to see the code coverage in the gutter alongside my code. and it can be done using just a few lines of configuration in Visual Studio Code. Well, I wanted the same feature in Rust too. After some research, I found a way to display code coverage in Rust as well. In this post, I will show you how to do it.
Before We Start
First, let's create a new Rust project:
Next, install nextest and cargo-llvm-cov using the following commands:
For Visual Studio Code, install the essential extensions:
Coding Time
Now, let's write some code and tests. In this example, I will write a simple function that calculates student grades.
Alright, we have written a simple function and a test for it. Now, let's run the tests and show the report in CLI:
If you want to see the coverage report in HTML format, just add the --open
flag:
Visual Studio Code Integration
First, you need to generate the coverage report in LCOV format using the following command:
Next, display the coverage from Coverage Gutters extension
Let's see the result:
From the above image, you can see the code coverage in the gutter. The green lines are covered, and the red lines are not covered. Now, you can easily identify which lines are not covered by tests. Can you spot the missing test case?
Tip
If you want to update the coverage report automatically when you change the code, you can use the cargo watch command.
That's it! Now you can see the code coverage in Visual Studio Code. I hope this post helps you to visualize code coverage in Rust. Happy coding!