Solidity

為什麼在針對 testrpc 執行時通過 Truffle 的測試會失敗

  • November 3, 2017

使用Truffle並對 Truffle 自己的區塊鍊和testrpc進行測試會產生不同的結果。

我正在嘗試測試我部署的契約是否owner正確設置(msg.sender在建構子中設置了所有者)

contract Cocktail {
 address public owner;

 function Cocktail() public {
   owner = msg.sender;
 }
}

我的遷移腳本就像

module.exports = (deployer, network, accounts) => {
 const superuser = accounts[0]
 console.log('Deploying to network', network, 'from', superuser)

 deployer.then(() => Cocktail.new({ from: superuser })).then((cocktail) => {
   console.log('Deployed Cocktail with address', cocktail.address)
 })
}

我的測試就像

const Cocktail = artifacts.require('./Cocktail.sol')

contract('Cocktail', (accounts) => {
 const superuser = accounts[0]

 it('is owned by superuser', () => Cocktail.deployed()
   .then(instance => instance.owner())
   .then((owner) => {
     assert.equal(owner, superuser, `Expected the owner to be '${superuser}'`)
   }))
})

如果我只是使用 Truffle 自己的區塊鏈並執行truffle developthen compile, migrate,那麼test一切都很好。

Contract: Cocktail
 ✓ is owned by superuser

如果我啟動testrpc並執行truffle test它聲稱可以遷移但測試失敗:

Using network 'development'.

Deploying to network development from 0x9aa5b3cee03060172ec9968a49857c2a68341f67
Deployed Cocktail with address 0x2294c2ef0db6994cf0c5a777e10e5be5e7aab69b

 Contract: Cocktail
   1) is owned by superuser
   > No events were emitted

 0 passing (86ms)
 1 failing

 1) Contract: Cocktail is owned by superuser:
    Error: Cocktail has not been deployed to detected network (network/artifact mismatch)

到底是怎麼回事?

此部署腳本適用於 testrpc 和內部區塊鏈

const Cocktail = artifacts.require("./Cocktail.sol");

module.exports = (deployer, network, accounts) => {
 const superuser = accounts[0];
 console.log('Deploying to network', network, 'from', superuser);

 deployer.deploy(Cocktail, { from: superuser }).then(() => {
   console.log('Deployed Cocktail with address', Cocktail.address);
 });
};

引用自:https://ethereum.stackexchange.com/questions/29834