CentOS7 - Truffle 创建、编译、部署、测试智能合约

本文详细记录了在CentOS7环境下配置Nodejs、Truffle和Ganache-cli,以及在过程中遇到的网络连接错误、合约创建、编译、部署、迁移和测试的完整步骤。在部署合约时,由于网络配置不全导致迁移失败,通过修改truffle-config.js文件中的网络配置解决了问题,并成功部署了Hello合约。测试合约时,展示了如何在Truffle控制台和通过编写JavaScript测试用例进行交互和验证。

注:在配置环境及部署合约时遇到诸多问题,这些问题及解决方案也做了记录,一些未成功的方法可略过,直接使用成功的方法。

0、前提条件

(1)安装Nodejs

参考 安装 Nodejs (CentOS7 与 Windows)_ling1998的博客-CSDN博客

(2)安装truffle

参考 安装 truffle (CentOS7 与 Windows)_ling1998的博客-CSDN博客

(3)安装与启动ganache-cli

[root@localhost truffle]# npm install -g ganache-cli #安装
npm WARN deprecated ganache-cli@6.12.2: ganache-cli is now ganache; visit https://trfl.io/g7 for details

added 1 package in 2s

2 packages are looking for funding
  run `npm fund` for details
[root@localhost truffle]# ganache-cli --version     #验证
Ganache CLI v6.12.2 (ganache-core: 2.13.2)
[root@localhost truffle]# ganache-cli               #启动
Ganache CLI v6.12.2 (ganache-core: 2.13.2)

Available Accounts
==================
(0) 0x0D74daF490f2CE8d7076C222B2bA02DC2Bd70d1F (100 ETH)
(1) 0x5382dFc9Ab55957aBd5b11B444eeCa948E8f680f (100 ETH)
(2) 0x74aFdE1344f8E5B72f1e63fE1220bC08E497B24e (100 ETH)
(3) 0x87ba7b1721C088B11D2b3bf6c450486B16e81723 (100 ETH)
(4) 0x4ad4B32368c55e974BA6D4cf2c15f26F76fDaAAc (100 ETH)
(5) 0x035aC96Ff68f6f0B0887BFFe6b9678bF0D682F4A (100 ETH)
(6) 0x05A9897E6431122e5dB2C8025076C6589F75a947 (100 ETH)
(7) 0x50A3D37093BB3395eCcb62C93401542e3cbb8aa9 (100 ETH)
(8) 0x9a33347df0003B4B947A8BcC951672bbB2F06746 (100 ETH)
(9) 0x5B9cb96fE1088F87D49a206B2cb50b70dD0A0cf9 (100 ETH)

Private Keys
==================
(0) 0x56dcb5e2883913947914f158a2df8c50ea297b7aa355e3bc8885f27de3e3da38
(1) 0x93a71ec1220e5e24313367458bb64e7b64a2959dd92c98c560b0c561b6be2031
(2) 0x0c57314e424c25d0565d9f27f71c647863372f202a9ff632e5b6d1cebeb99ff2
(3) 0x9f665239c7fe30bc377f70a6f3ac22635eabfcd52a97644c8eeb1bcf1c1a3510
(4) 0x7c4d94eb745963a09bd864db858ba4b7c9ed2c35b8170454a04290a2821a2b09
(5) 0x9efd2a49c773f9947972bf580ec9646c1041506c4a7b5f7d713060034a1d697a
(6) 0x6e502d9dc020df25664c63abe1d6a6d045159f3e4fa7d6413ecd352bd5ba4e1b
(7) 0x168cb1c38a65de24da9451ccb09a5eff8e0daf0f704d807af26b61f6dcc3bc2c
(8) 0x2d07672e8d4cb3eff9a0d28d78f2198684c6ed2789aa2655f8189de63db28f8f
(9) 0xdf4dc37882c66edab55234f14404f57e29bb6554198c48942674010f3cc3d059

HD Wallet
==================
Mnemonic:      code evil field such lizard nest month dune glare trap hurdle cry
Base HD Path:  m/44'/60'/0'/0/{account_index}

Gas Price
==================
20000000000

Gas Limit
==================
6721975

Call Gas Limit
==================
9007199254740991

Listening on 127.0.0.1:8545

1、创建工程

以下1~3方法都未成功,可直接看方法4。 

(1)使用truffle unbox metacoin(未成功)

官网使用truffle unbox metacoin,就是将这些盒子下载到本地,但是报错,如下所示:

[root@localhost truffle]# truffle unbox metacoin

Starting unbox...
=================

✔ Preparing to download box
✖ Downloading
Unbox failed!
✖ Downloading
Unbox failed!
RequestError: Error: connect ECONNREFUSED 0.0.0.0:443
    at new RequestError (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request-promise-core/lib/errors.js:14:1)
    at Request.plumbing.callback (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request-promise-core/lib/plumbing.js:87:1)
    at Request.RP$callback [as _callback] (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request-promise-core/lib/plumbing.js:46:1)
    at self.callback (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request/request.js:185:1)
    at Request.emit (node:events:526:28)
    at Request.onRequestError (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request/request.js:881:1)
    at ClientRequest.emit (node:events:526:28)
    at TLSSocket.socketErrorListener (node:_http_client:442:9)
    at TLSSocket.emit (node:events:526:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Truffle v5.1.13 (core: 5.1.13)
Node v16.14.2

(2)使用truffle init(未成功)

[root@localhost truffle]# truffle init

Starting unbox...
=================

✔ Preparing to download box
✖ Downloading
Unbox failed!
✖ Downloading
Unbox failed!
RequestError: Error: connect ECONNREFUSED 0.0.0.0:443
    at new RequestError (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request-promise-core/lib/errors.js:14:1)
    at Request.plumbing.callback (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request-promise-core/lib/plumbing.js:87:1)
    at Request.RP$callback [as _callback] (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request-promise-core/lib/plumbing.js:46:1)
    at self.callback (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request/request.js:185:1)
    at Request.emit (node:events:526:28)
    at Request.onRequestError (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/node_modules/request/request.js:881:1)
    at ClientRequest.emit (node:events:526:28)
    at TLSSocket.socketErrorListener (node:_http_client:442:9)
    at TLSSocket.emit (node:events:526:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
Truffle v5.1.13 (core: 5.1.13)
Node v16.14.2

(3)通过git下载metacoin-box(未成功)

[root@localhost truffle]# git clone https://github.com/truffle-box/metacoin-box.git
Cloning into 'metacoin-box'...
fatal: unable to access 'https://github.com/truffle-box/metacoin-box.git/': Failed connect to github.com:443; Connection refused

(4)通过git下载react-box(成功)

[root@localhost truffle]# git clone https://github.com/truffle-box/react-box.git
Cloning into 'react-box'...
remote: Enumerating objects: 623, done.
remote: Counting objects: 100% (165/165), done.
remote: Compressing objects: 100% (143/143), done.
remote: Total 623 (delta 109), reused 44 (delta 22), pack-reused 458
Receiving objects: 100% (623/623), 1.80 MiB | 1.02 MiB/s, done.
Resolving deltas: 100% (314/314), done.

目录结构如下图所示:

2、编写合约

(1)进入合约目录

[root@localhost truffle]# cd react-box/contracts/

(2)创建合约文件

[root@localhost contracts]# truffle create contract Hello

 注:使用truffle命令创建合约文件,文件会根据合约模板合约内容,如下所示:

pragma solidity >= 0.5.0 < 0.7.0;

contract Hello {
  constructor() public {
  }
}

(3)编写合约

可以使用VSCode编写合约,或通过命令vi Hello.sol编写合约,合约内容如下: 

pragma solidity >= 0.5.0 < 0.7.0;

contract Hello {
  string value;
  constructor(string memory _value) public {
    value = _value;
  }

  function getValue() public view returns (string memory) {
    return value;
  }

  function setValue(string memory _value) public {
    value = _value;
  }
}

注:getValue() 需要修饰符view,returns string类型需要加memory 

3、编译合约

[root@localhost contracts]# truffle compile Hello.sol

Compiling your contracts...
===========================
> Compiling ./contracts/Hello.sol
> Artifacts written to /home/tracy/GoContract/truffle/react-box/client/src/contracts
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

4、迁移合约(部署合约)

(1)进入迁移目录

[root@localhost contracts]# cd ../migrations/

(2)生成迁移文件

[root@localhost migrations]# truffle creae migration deploy_hello
[root@localhost migrations]# ls -l
total 12
-rw-r--r--. 1 root root  86 Apr 13 15:08 1649833737_deploy_hello.js
-rw-r--r--. 1 root root 129 Apr 13 13:54 1_initial_migration.js
-rw-r--r--. 1 root root 138 Apr 13 13:54 2_deploy_contracts.js

生成的文件前面加了一串数字,查看文件1649833737_deploy_hello.js,内容如下:

module.exports = function(_deployer) {
  // Use deployer to state migration tasks.
};

(3)编写迁移文件

可以仿照迁移目录中的1_initial_migration.js文件修改生成的迁移文件,1_initial_migration.js内容如下:

var Migrations = artifacts.require("./Migrations.sol");

module.exports = function(deployer) {
  deployer.deploy(Migrations);
};

修改1649833737_deploy_hello.js内容如下:

var Migrations = artifacts.require("./Hello.sol");

module.exports = function(_deployer) {
  // Use deployer to state migration tasks.
  _deployer.deploy(Migrations,"hello");
};

注:参数为_deployer,有下划线_,这与1_initial_migration.js中的参数有些不同,否则迁移时会报错 ReferenceError: deployer is not defined。

更新部署相关配置(即.deploy函数)可参见:合约部署(Migrations) | Truffle 中文文档 - DApp 开发框架 | 深入浅出区块链

(4)迁移合约(部署合约)

[root@localhost react-box]# truffle migrate

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

> Something went wrong while attempting to connect to the network. Check your network configuration.

Could not connect to your Ethereum client with the following parameters:
    - host       > 127.0.0.1
    - port       > 7545
    - network_id > 5777
Please check that your Ethereum client:
    - is running
    - is accepting RPC connections (i.e., "--rpc" option is used in geth)
    - is accessible over the network
    - is properly configured in your Truffle configuration file (truffle-config.js)

Truffle v5.1.13 (core: 5.1.13)
Node v16.14.2

以上错误是因为truffle-config.js的配置不完全导致,truffle-config.js默认为:

const path = require("path");

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  contracts_build_directory: path.join(__dirname, "client/src/contracts"),
  networks: {
    develop: {
      port: 8545
    }
  }
};

需要增加及调整:

A、增加 - 主机地址(host)

B、增加 - 部署合约的账户地址(from)

     可从启动的ganache-cli中复制一个账户地址

     注: 不增加会报错:"Migrations" -- Returned error: sender account not recognized. (详见下面的错误1)

C、增加 - 配置网络ID(network_id)

    network_id值为*,即匹配所有网络

D、修改 - devlop 为 development

     注: 不修改使用truffle migrate执行与上面错误相同,可使用 truffle migrate --network develop (详见下面的错误2)

const path = require("path");

module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
  contracts_build_directory: path.join(__dirname, "client/src/contracts"),
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      from: "0x0D74daF490f2CE8d7076C222B2bA02DC2Bd70d1F",
      network_id: "*"
    }
  }
};

错误1 :不增加B - 部署合约的账户地址

错误信息如下:

[root@localhost react-box]# truffle migrate

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



Starting migrations...
======================
> Network name:    'development'
> Network id:      1649838459352
> Block gas limit: 0x6691b7


1_initial_migration.js
======================

   Deploying 'Migrations'
   ----------------------

Error:  *** Deployment Failed ***

"Migrations" -- Returned error: sender account not recognized.

    at /usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/deployer/src/deployment.js:364:1
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at Migration._deploy (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/migrate/migration.js:70:1)
    at Migration._load (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/migrate/migration.js:57:1)
    at Migration.run (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/migrate/migration.js:167:1)
    at Object.runMigrations (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:148:1)
    at Object.runFrom (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:110:1)
    at Object.run (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/migrate/index.js:87:1)
    at runMigrations (/usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:253:1)
    at /usr/local/node-v16.14.2-linux-x64/lib/node_modules/truffle/build/webpack:/packages/core/lib/commands/migrate.js:218:1
Truffle v5.1.13 (core: 5.1.13)
Node v16.14.2

错误2 :不修改D - truffle-config.js中的develop

与第(4)步刚开始的错误一样,错误信息如下:

[root@localhost react-box]# truffle migrate

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

> Something went wrong while attempting to connect to the network. Check your network configuration.

Could not connect to your Ethereum client with the following parameters:
    - host       > 127.0.0.1
    - port       > 7545
    - network_id > 5777
Please check that your Ethereum client:
    - is running
    - is accepting RPC connections (i.e., "--rpc" option is used in geth)
    - is accessible over the network
    - is properly configured in your Truffle configuration file (truffle-config.js)

Truffle v5.1.13 (core: 5.1.13)
Node v16.14.2

可使用 --network 指定网络部署合约,这样就不用改develop了。

[root@localhost react-box]# truffle migrate --network develop

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



Starting migrations...
======================
> Network name:    'develop'
> Network id:      1649838459352
> Block gas limit: 0x6691b7


1_initial_migration.js
======================

   Replacing 'Migrations'
   ----------------------
   > transaction hash:    0x71e938269ce53553c5e7365ef75c9cebcc1997408eff72587e7f35e5f7e2c8dc
   > Blocks: 0            Seconds: 0
   > contract address:    0x4a76504fF94ED9bBBe0e091151BE76684156b022
   > block number:        58
   > block timestamp:     1649871425
   > account:             0x0D74daF490f2CE8d7076C222B2bA02DC2Bd70d1F
   > balance:             99.6865259
   > gas used:            164175
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.0032835 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:           0.0032835 ETH


2_deploy_contracts.js
=====================

   Replacing 'SimpleStorage'
   -------------------------
   > transaction hash:    0xca584133d05b727eba0e11c3e8d693a9514bb24d72a78aa00e342b2014bd593e
   > Blocks: 0            Seconds: 0
   > contract address:    0x7EF86dd0248cB9B800a1a7930Df17789d4ddae25
   > block number:        60
   > block timestamp:     1649871425
   > account:             0x0D74daF490f2CE8d7076C222B2bA02DC2Bd70d1F
   > balance:             99.6837553
   > gas used:            96189
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00192378 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00192378 ETH


1649833737_deploy_hello.js
==========================

   Replacing 'Hello'
   -----------------
   > transaction hash:    0xf1b1fe3c65c518fe754c69cb6f492fe25a35efd7d41a0df9e7a826a917567160
   > Blocks: 0            Seconds: 0
   > contract address:    0x7527BF40a29EA90E2f8b454ee9Bb09880A92A27f
   > block number:        62
   > block timestamp:     1649871426
   > account:             0x0D74daF490f2CE8d7076C222B2bA02DC2Bd70d1F
   > balance:             99.6781922
   > gas used:            250814
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00501628 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00501628 ETH


Summary
=======
> Total deployments:   3
> Final cost:          0.01022356 ETH

迁移(部署)成功

按上面修改好配置文件truffle-config.js,再次执行迁移命令,成功啦!!!

[root@localhost react-box]# truffle migrate

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



Starting migrations...
======================
> Network name:    'development'
> Network id:      1649838459352
> Block gas limit: 0x6691b7


1649833737_deploy_hello.js
==========================

   Deploying 'Hello'
   -----------------
   > transaction hash:    0xd8aa53babe3b99def174639cdde4b1906dc4bb555f968c63a9628a6b4b6913d5
   > Blocks: 0            Seconds: 0
   > contract address:    0x8c69e3692FcEF865760cF19482e9A9d1f0eb2aE8
   > block number:        5
   > block timestamp:     1649843534
   > account:             0x0D74daF490f2CE8d7076C222B2bA02DC2Bd70d1F
   > balance:             99.9883828
   > gas used:            250814
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00501628 ETH


   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00501628 ETH


Summary
=======
> Total deployments:   1
> Final cost:          0.00501628 ETH

5、测试合约

方法一:使用truffle控制台 

(1)进入truffle控制台

[root@localhost react-box]# truffle console
truffle(development)> exit

(2)创建合约实例

truffle(development)> let instance = await Hello.deployed("hello")
undefined

(3)查看实例

truffle(development)> instance
TruffleContract {
  constructor: [Function: TruffleContract] {
    _constructorMethods: {
      configureNetwork: [Function: configureNetwork],
      setProvider: [Function: setProvider],
      new: [Function: new],
      at: [AsyncFunction: at],
      deployed: [AsyncFunction: deployed],
      defaults: [Function: defaults],
      hasNetwork: [Function: hasNetwork],
      isDeployed: [Function: isDeployed],
      detectNetwork: [AsyncFunction: detectNetwork],
      setNetwork: [Function: setNetwork],
      setNetworkType: [Function: setNetworkType],
      setWallet: [Function: setWallet],
      resetAddress: [Function: resetAddress],
      link: [Function: link],
      clone: [Function: clone],
      addProp: [Function: addProp],
      toJSON: [Function: toJSON],
      decodeLogs: [Function: decodeLogs]
    },
    _properties: {
      contract_name: [Object],
      contractName: [Object],
      gasMultiplier: [Object],
      timeoutBlocks: [Object],
      autoGas: [Object],
      numberFormat: [Object],
      abi: [Object],
      metadata: [Function: metadata],
      network: [Function: network],
      networks: [Function: networks],
      address: [Object],
      transactionHash: [Object],
      links: [Function: links],
      events: [Function: events],
      binary: [Function: binary],
      deployedBinary: [Function: deployedBinary],
      unlinked_binary: [Object],
      bytecode: [Object],
      deployedBytecode: [Object],
      sourceMap: [Object],
      deployedSourceMap: [Object],
      source: [Object],
      sourcePath: [Object],
      legacyAST: [Object],
      ast: [Object],
      compiler: [Object],
      schema_version: [Function: schema_version],
      schemaVersion: [Function: schemaVersion],
      updated_at: [Function: updated_at],
      updatedAt: [Function: updatedAt],
      userdoc: [Function: userdoc],
      devdoc: [Function: devdoc],
      networkType: [Object]
    },
    _property_values: {},
    _json: {
      contractName: 'Hello',
      abi: [Array],
      metadata: '{"compiler":{"version":"0.5.16+commit.9c3226ce"},"language":"Solidity","output":{"abi":[{"inputs":[{"internalType":"string","name":"_value","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"constant":true,"inputs":[],"name":"getValue","outputs":[{"internalType":"string","name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"string","name":"_value","type":"string"}],"name":"setValue","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}],"devdoc":{"methods":{}},"userdoc":{"methods":{}}},"settings":{"compilationTarget":{"/home/tracy/GoContract/truffle/react-box/contracts/Hello.sol":"Hello"},"evmVersion":"istanbul","libraries":{},"optimizer":{"enabled":false,"runs":200},"remappings":[]},"sources":{"/home/tracy/GoContract/truffle/react-box/contracts/Hello.sol":{"keccak256":"0x9cc44b2db470d046185db272796bab593e75c9b94d9633c3d03c7b03d0795f6e","urls":["bzz-raw://4d4c6581c0f9349b5d8e24a14e4888f9a7d06513e2f083e5ce9ccbab24b371a7","dweb:/ipfs/QmcYQpVSB28H9UoiSatAKqPegWKyRsoAvSwCJSBiwQNH6g"]}},"version":1}',
# 以下输出的信息省略,太多了......

(4)调用函数 

调用getValue函数 :

truffle(development)> instance.getValue()
'hello'

调用setValue函数,设置新值: 

truffle(development)> instance.setValue("I am tracy")
{
  tx: '0x5b16de0a0cdf03b950701c3b44b4cbd8a7c6e4cb4a89c8416dd34a83b4c3db15',
  receipt: {
    transactionHash: '0x5b16de0a0cdf03b950701c3b44b4cbd8a7c6e4cb4a89c8416dd34a83b4c3db15',
    transactionIndex: 0,
    blockHash: '0xdf95a90bc7f9cd314bb8666d0aba54b3f906f756b68180b2d268438caa3f6592',
    blockNumber: 7,
    from: '0x0d74daf490f2ce8d7076c222b2ba02dc2bd70d1f',
    to: '0x8c69e3692fcef865760cf19482e9a9d1f0eb2ae8',
    gasUsed: 29155,
    cumulativeGasUsed: 29155,
    contractAddress: null,
    logs: [],
    status: true,
    logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
    rawLogs: []
  },
  logs: []
}

再次调用getValue函数,发现值已经改变: 

truffle(development)> instance.getValue()
'I am tracy'

(5)退出控制台

truffle(development)> .exit

方法二:使用Javascript编写测试用例

(1)编写测试用例

[root@localhost react-box]# vi test/TestHello.js 

测试用例内容如下:

contract("Hello",accounts => {
  it("...should output value.",async() => {
    const helloInstance = await Hello.deployed();

    let newValue = "I am tracy,and I am testing Truffle test by using javascript";
    
    //set value
    await helloInstance.setValue(newValue);
    
    //get value
    const value = await helloInstance.getValue.call();

    assert.equal(value,newValue,"The value was not changed.");
  });
});

按Esc退出编辑,输入:wq保存退出。 

(2)执行测试用例

[root@localhost react-box]# truffle test test/TestHello.js
Using network 'development'.


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



  Contract: Hello
    ✓ ...should output value. (110ms)


  1 passing (137ms)

方法三:使用Solidity编写测试用例

(1)编写测试用例

[root@localhost react-box]# vi test/TestHello.sol

 测试用例内容如下:

pragma solidity >=0.4.21 <0.7.0;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Hello.sol";

contract TestHello {
  function testSetValue() public {

    Hello hello = Hello(DeployedAddresses.Hello());

    string memory newValue = "I am Tracy, I am testing Truffle test by using solidity";

    //set value
    hello.setValue(newValue);

    Assert.equal(hello.getValue(), newValue, "The value is not changed.");
  }

}

按Esc退出编辑,输入:wq保存退出。

(2)执行测试用例

[root@localhost react-box]# truffle test test/TestHello.sol 
Using network 'development'.


Compiling your contracts...
===========================
> Compiling ./test/TestHello.sol
> Artifacts written to /tmp/test-2022314-38527-1f1x7gm.ld8j
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang



  TestHello
    ✓ testSetValue (82ms)


  1 passing (5s)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值