Truffle for smart contract testing

other dependencies

node.js、

Since it is performed using npm, first set up the domestic mirror source. search online

1. Install truffle

npm install truffle -g

truffle --version
安装完其他项目依赖,能够产生一下效果

2. Project creation

创建test文件夹
mkdir test

进入test
cd test

初始化项目
truffle init

 

contracts : Folder for writing and storing smart contracts

migrations : Use solidity to write the folder of smart contracts, and write files to explain how truffle deploys smart contracts, using node.js

test : used to write test files, most of them use node.js, and some use Solidity

truffle-config.js : The configuration file is used to define the network for smart contract deployment

3. Edit contract

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <=0.9.0; //请注意solidity的版本问题,如果合约指定的版本和当前Solidity不兼容的话,这将会在编译的时候出错

contract Test {
    uint data;

    function updateData(uint _data) external {
        data = _data;
    }

    function readData() external view returns (uint) {
        return data;
    }
}

4. Compile the contract

        

5. Deploy the contract

Ganache can be installed independently, but when truffle is installed, ganache will also be installed automatically, and the written and tested smart contracts can be deployed to the private chain or the Ethereum test network.

 1. Write the test_deploy.js migration file


const Test = artifacts.require("Test");

module.exports = function (deployer) {
    deployer.deploy(Test);
};
2. Edit the truffle-config.js file

This corresponds to the configuration of Ganache.

3. Deploy the contract
truffle migrate

 6. Contract testing

will recompile and deploy

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

contract('Test', () => {
    it('Should update data', async () => {
        const newTest = await Test.new();
        await newTest.updateData(10);
        const data = await newTest.readData();
        assert(data.toString() === '10',"failed!");
    });
});

 

Guess you like

Origin blog.csdn.net/Qhx20040819/article/details/131897769