I am new to Solidity, and I am trying to create my first smart contract following the ERC-20 token standard. As the standard requires, I have a transfer
function which looks like following:
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
// transfer the amount
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
// trigger a Transfer event
emit Transfer(msg.sender, _to, _value);
return true;
}
As can be seen, I am first doing a sanity check that the sender has sufficient amount to perform a transaction with require(balanceOf[msg.sender] >= _value)
. I now want to test that specific part of the code to see if it will actually throw an expected error if the amount is too large. I am doing it using truffle
with a helpful truffle-assertions package:
const truffleAssert = require("truffle-assertions");
it("should revert transfer if the amount is larger than the sender's balance", () => {
return MyToken.deployed().then((instance) =>
truffleAssert.fails(
instance.transfer.call(accounts[1], 10000000),
truffleAssert.ErrorType.REVERT
)
);
});
This seems to be working as expected. However, if I were to remove the require
part from my transfer
function, I would expect the test to fail, but the test somehow passes. Coming from a Java background, this leaves me doubtful of whether I am actually testing the code properly or not. What is the correct and robust way of testing such scenarios in Solidity?