0

For example I have a smart contract with 2 attributes:

contract SimpleSmartContract {
    uint256 currentPrices;
    mapping(uint8 => uint256) public priceIncrements;
}

When I write test, I want to test some situations (depends on the state of attributes). My question is: How can I setup data for those variables before running tests. (i.e: set currentPrices to 100, and set up map to some data before).

Thanks

2

One trick that I use is to create a test contract that inherit from my contract. I create a method that will setup the correct values

contract SimpleSmartContractTest is SimpleSmartContract {
    function setup() public {
        currentPrices = 1234;
        priceIncrements[1] = 100;
        priceIncrements[2] = 110;
        priceIncrements[3] = 120;
    }
}

Now I when running my test I create an instance of SimpleSmartContractTest but because it inherit from SimpleSmartContract all methods are available.

const SimpleSmartContractTest = artifacts.require('SimpleSmartContractTest');

contract('SimpleSmartContract', (accounts) => {
    let simpleSmartContract;
    before(async () => {
        simpleSmartContract = await SimpleSmartContractTest.new(constructorParams..)
        await simpleSmartContract.setup(setupParams..)
    })
    it('Transfer', async () => {
        // Here test like it was SimpleSmartContract
        const result = await simpleSmartContract.transfer(accounts[1], 100, 
            { from: accounts[0] })
        assert.equal(result.logs[0].event, 'Transfer', 'Transfer should succeed')
    })
})
  • nice trick. I can make some "helper" method in this contract also. :D I have a scenario that I want to assert some state of smart contract, ie: balance[address]. How can you achieve this ? By writing helper method on mock contract also ? thanks. – hqt Apr 29 '18 at 5:45
  • @hqt Since it is a contract you can add more functions. The only issue might be that you cannot access private functions nor variables in the base contract. But otherwise you can access internal and public functions. – Ismael Apr 29 '18 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.