For smart contract developers, writing contract tests is a very important skill. Maybe we don't need to be as rigorous as auditing, but testing must cover all functions. Code Coverage is usually needed to view the coverage.
Here, I recommend a plugin for VS Code called Coverage Gutters. It can locate the code covered/uncovered by your tests based on the Code Coverage Report file you generated, and prompt it in front of the line, making test writing more efficient.
Demo#
I use Foundry to create smart contract projects and perform contract testing.
mkdir demo && cd demo
forge init
After project initialization, the directory structure is as follows:
.
├── README.md
├── foundry.toml
├── lib
│ └── forge-std
├── script
│ └── Counter.s.sol
├── src
│ └── Counter.sol
└── test
└── Counter.t.sol
6 directories, 5 files
Counter.sol contract file and the corresponding Counter.t.sol test file are automatically generated.
Install Coverage Gutters from the VS Code plugin marketplace.
Use Foundry to generate Code Coverage Report.
forge coverage --report lcov
Then you will find a lcov.info file generated.
After locating the window to the src/Counter.sol file, click on watch at the bottom.
You can see that there is a green mark in front of the lines of code that have been covered by the test, and the coverage rate is displayed at the bottom as 100%.
Modify test/Counter.t.sol and add a function.
function decrease() public {
number--;
}
Update the Code Coverage Report.
forge coverage --report lcov
You will find that there is a red mark in front of the newly added untested function, and the coverage rate at the bottom becomes 67%.