Truffle合约测试

合约测试 truffle test

测试文件应置于./tests目录。Truffle只会运行以.js,.es,.es6和.jsx结尾的测试文件,其它的都会被忽略。

命令

要执行测试,执行下面的命令

truffle test

你也可以对单个文件执行测试:

–network development 选择网络,配置在truffle-config.js内

truffle test ./path/to/test/file.js --network development

编写一个合约

pragma solidity  0.5.16;

contract Greeter {
    address private creator;
    string private greeting;

    constructor (string memory _greeting) public
    {
        creator = msg.sender;
        greeting = _greeting;
    }

    function getGreeting() public view returns (string memory)
    {
        return greeting;
    }

    function setGreeting(string memory _newGreeting ) public
    {
        greeting = _newGreeting;
    }

}

测试Case,以下是以异步的方式实现
在对于的测试目录下面新增文件GreeterTest.js,内容如下

const Greeter  = artifacts.require('Greeter.sol');
//执行变量,便于进行更改
const var_a = 'hello';
const var_b = 'Hello World';
//执行定义合约中的其他操作
contract('Greeter',accounts => {
    
    
    before(async () => {
    
    
        //构建合约(可以设置两种方式)
        //01
        let a = await Greeter.deployed();
        //02
        //let Contract_Ches       = await Ches.new(var_a);
        let c = await a.getGreeting();
        let d = await a.setGreeting(var_b);
        let f = await a.getGreeting();

        
        //在原有的合约上进行获取
        let g = await Greeter.at('0x592C0067a4B3Fc66D7f26430b3EBeF9ac7796F85');
        let h = await g.getGreeting();
        let i = await g.setGreeting('您好,世界!');
        let k = await g.getGreeting();
        console.log("合约地址:",a.address);
        console.log("获取原数据:",c);
        console.log("获取新数据:",f);
        console.log("获取原来的合约地址:",g.address);


        console.log("获取原来的合约值:",h);
        console.log("更改原来合约的值,并且显示出来:",k);
        // console.log("02合约地址:",Contract_Ches.address);
    });


    it('Check whether the contract has been issued successfully', async () => {
    
    
      console.log("测试合约的操作:");
    }); 
});

运行

PS E:\workspace\KnowledgeManagement\BlockChain\Solidity\study\truffle> truffle test --network development  ./test/GreeterTest.js
Using network 'development'.


Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.



  Contract: Greeter
合约地址: 0xCE6D5dBC7905Ff62dDb1377b92b82Ecf10BB3596
获取原数据: kevin
获取新数据: Hello World
获取原来的合约地址: 0x592C0067a4B3Fc66D7f26430b3EBeF9ac7796F85
获取原来的合约值: Hello World
更改原来合约的值,并且显示出来: 您好,世界!
测试合约的操作:
    √ Check whether the contract has been issued successfully


  1 passing (485ms)

PS E:\workspace\KnowledgeManagement\BlockChain\Solidity\study\truffle>

猜你喜欢

转载自blog.csdn.net/jc0803kevin/article/details/109101913
今日推荐