Solidity unit tests & code coverage with Etherlime
An easy way to test your solidity smart contracts.
Written by: Veselin Savov of LimeChain
Hey all, I want to share with you an easy way to test your smart contracts. Currently Ethereum ecosystem is still in development. A lot of tools are still missing. But for our luck there is Etherlime. Now I will show how to write tests and run code coverage with Etherlime.
First you need to install Etherlime. Open your project folder and run this commands.
npm i -g etherlime
etherlime init
Let’s write a simple contract that we will be test.
Write tests
When you open test/exampleTest.js you will find this code
Add some requires.
SimpleContract — path to your compiled contract
ethers — ether js lib
expectThrow — if you have cases where you want expect errors you may copy code from below.
If you are getting out of gas exception you will need to override default gasLimit.
Etherlime passes 10 accounts with million ethers. Each account object contains privateKey and wallet.
Let’t add beforeEach which will be called before test.
EtherlimeGanacheDeployer takes 3 params:
- private key of wallet which will be used to deploy contracts
- port of ganache
- overrideOptions
And this is our first test case.
One more test and full code of exampleTest.js
If you want to call contract from a different account you may use ethers js
var contract = new ethers.Contract(simpleContractDeployed.contract.address, SimpleContract.abi, secondAccount.wallet);
Run tests
To run exampleTest.js you need to start ganache. Open your cmd/terminal and run this command:
etherlime ganache
Open one more cmd/terminal and go to your project directory.
Run etherlime test command. Before each run all contract are recompiled. If you want to compiler to optimize your code pass runs={number}
etherlime test --runs=999
You should see something similar.
Run code coverage
Again open your cmd/terminal and go to you project dir.
etherlime coverage --runs=999
You should see something similar.
If you have uncovered code you will see something similar
If you have any questions feel free to comment and ask me :)