{"content":{"title":"使用 Coverage Gutters 更好地检查合约 Code Coverage","body":"对于智能合约开发者来说，编写合约测试是非常重要的一项技能。或许我们不需要像审计那样严谨，但测试一定要覆盖到所有功能。通常需要 Code Coverage 来查看覆盖率。\r\n\r\n这里推荐 VS Code 的一款插件 [Coverage Gutters](https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters) 它可以根据你所生成的 Code Coverage Report 文件定位你测试已覆盖/未覆盖的代码，并在行前提示出来，使得编写测试更加高效。\r\n\r\n## 演示\r\n\r\n笔者使用 [Foundry](https://learnblockchain.cn/docs/foundry/i18n/zh/) 来创建智能合约项目并进行合约测试。\r\n\r\n```bash\r\nmkdir demo && cd demo\r\nforge init\r\n```\r\n\r\n项目初始化后目录结构如下：\r\n\r\n```bash\r\n.\r\n├── README.md\r\n├── foundry.toml\r\n├── lib\r\n│   └── forge-std\r\n├── script\r\n│   └── Counter.s.sol\r\n├── src\r\n│   └── Counter.sol\r\n└── test\r\n    └── Counter.t.sol\r\n\r\n6 directories, 5 files\r\n```\r\n\r\n自动生成了 Counter.sol 合约文件与对应的 Counter.t.sol 测试文件\r\n\r\n去 VS Code 的插件市场安装 Coverage Gutters \r\n\r\n![coverage-gutters.png](https://img.learnblockchain.cn/attachments/2023/10/aJv0L1sk65213e388bb19.png)\r\n\r\n使用 Foundry 生成 Code Coverage Report\r\n\r\n```bash\r\nforge coverage --report lcov\r\n```\r\n\r\n然后会发现生成了一个 lcov.info 文件\r\n\r\n窗口定位到 src/Counter.sol 文件后，点击底部的 `watch`\r\n\r\n![watch.png](https://img.learnblockchain.cn/attachments/2023/10/oMADoSwe65213e47b0775.png)\r\n\r\n可以发现在测试已经覆盖到的代码行前出现绿色标记，同时底部显示覆盖率 100%\r\n\r\n![shot-1.png](https://img.learnblockchain.cn/attachments/2023/10/dzvDwE6x65213e5603e48.png)\r\n\r\n修改 test/Counter.t.sol 添加函数\r\n\r\n```solidity\r\nfunction decrease() public {\r\n\tnumber--;\r\n}\r\n```\r\n\r\n更新 Code Coverage Report\r\n\r\n```bash\r\nforge coverage --report lcov\r\n```\r\n\r\n会发现新增的未测试函数行前出现红色标记，底部覆盖率变为 67%\r\n\r\n![shot-2.png](https://img.learnblockchain.cn/attachments/2023/10/fW4mUVw765213e5e27a88.png)"},"author":{"user":"https://learnblockchain.cn/people/5673","address":null},"history":"QmRmg4MFLtKJDiWuXHp13Y6uh5Jy57q7TdnGYmp39LNfci","timestamp":1696687870,"version":1}