Solidity Unit Testing – Using Different Accounts for Executing a Function

msg.sendersolidityunittesting

I have written a smart contract and within which I have declared a payable function where everyone could send their funds to the contract. Once they have transferred their funds, they would have the allowance to use some other features. However, now I want to write a solidity unit test for the script to test its functions when different accounts send funds through. I wanted to know whether there is any way to modify the msg.sender while executing functions of solidity unit testing. For instance, account 1 sends eth to contract, then account 2 needs to do the same.

Best Answer

As mentioned in the comments, common development frameworks (Hardhat, Truffle) provide you with multiple accounts. You can't spoof msg.sender in contracts, but you can change which account sends a transaction in the unit test.

This, of course, works easiest in your own local blockchains. Yes, you can import multiple accounts for public networks, but that's not how it's usually done.

With Hardhat, there are good examples in their documentation: https://hardhat.org/tutorial/testing-contracts.html#using-a-different-account . Hardhat gives each of those test accounts enough local Ether for any testing you want to do (1000 or so). To switch to use a different account, use the connect function, as shown in the examples.

Related Topic