For smart contract developers, writing contract tests is a very important skill. Perhaps we don't need to be as rigorous as auditing, but testing must cover all functionalities. Code Coverage is usually needed to view the coverage.
Here, I recommend a plugin called Coverage Gutters for VS Code. It can locate the code covered/uncovered by your generated Code Coverage Report file and provide prompts before the lines, 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 its corresponding Counter.t.sol test file are automatically generated.
Install Coverage Gutters from the VS Code plugin marketplace.
Generate Code Coverage Report using Foundry.
forge coverage --report lcov
Then you will find a lcov.info file generated.
After locating the window to src/Counter.sol file, click on "watch" at the bottom.
You will see green markers appearing before the lines of code that have been covered by the tests, and the coverage rate is displayed as 100% at the bottom.
Modify test/Counter.t.sol and add a function.
function decrease() public {
number--;
}
Update the Code Coverage Report.
forge coverage --report lcov
You will see red markers appearing before the lines of the newly added untested function, and the coverage rate becomes 67% at the bottom.