Writing tests in Solidity

  1. You should write tests just like a contract, and the contract name should start with Test, using an uppercase T. It uses the clean room environment just like the JavaScript test cases:
contract TestContract {
...
}
  1. Write individual functions to represent each test case that must start with test, using a lowercase t. Each function is executed by a single transaction in the same order as the declaration:
contract TestContract {
testCase1() { ... }
testCase2() { ... }
}

  1. Use the Assert.sol library provided by Truffle to handle the assertions. Import it from truffle/Assert.sol. You can replace the library with your custom made one, but it should follow the exact signature of Assert.sol:
import "truffle/Assert.sol";
  1. Assertion functions emit events that the test framework evaluates to determine the result of the test. These functions return a Boolean value, which represents the outcome of the assertion.

  2. Consider the following test example, which checks for the balance of an account:
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/TokenContract.sol";

contract TestTokenContract {

function testInitialBalance() {
TokenContract token =
TokenContract(DeployedAddresses.TokenContract());

uint expected = 100000;

Assert.equal(token.getBalance(msg.sender),
expected,
"Owner should have 100000 TokenContract initially");
}

}
  1. Solidity test cases also include various hook functions, similar to Mocha. These hooks are beforeAll, beforeEach, afterAll, and afterEach. Use these hooks to perform actions before and after each test case or test suit.

  2. You can even write the same hook multiple times, each with an additional suffix. This will help you to write a complex setup process that might use a lot of gas:
import "truffle/Assert.sol";

contract TestHooks {

uint value;

function beforeEach() {
value = 1;
}

function beforeEachIncrement() {
value++;
}

function testSomeValue() {
uint expected = 2;

Assert.equal(value, expected, "value should be 2");
}
}
  1. Execute the tests with the truffle test command. It will display the result similar to JavaScript test cases in the console.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.249.198