- Published on
Getting accounts to use in truffle tests
- Authors
- Name
- Yair Mark
- @yairmark
When testing a Solidity contract you often need to work with one or more accounts. When running Ganache a number of accounts are created together with Ether in each of these accounts. The problem is every time you run Ganache those accounts change so you cannot simply hard code those values otherwise you get the error: Error: sender account not recognized
.
After reading through the Truffle docs on testing I found this. Based on this information I updated my tests as follows:
contract('YourContractsNameWithoutSol', ([owner, account1, account2, account3, account4]) => {
//your testing code here
})
In the above I use ES6 array destructuring to more cleanly specify the names of each account. You can name these accounts whatever makes sense in your application. It is important to note that accounts[0] i.e. the first parameter in the array is the owner or the person running the contract in tests. It is also important that you use Truffle's contract to define your tests otherwise if you use describe
(which you can further in the tests) you lose access to this accounts
array as well as a number of other features as described here.