Solidity

為什麼我不能用松露檢測可靠性錯誤?

  • December 5, 2018

我正在測試 ERC20 標準。我嘗試從餘額 = 0 的帳戶發送交易,這應該會引發錯誤。我試圖抓住它。

在我的測試功能中,我使用以下內容:

contract('erc20 deployed', function(accounts) {
   it("should not transfer 1 token from address[0] to address[1]", function(done) {
       try{
           return erc20Instance.transfer(accounts[1], 1);
           should.fail("No error was thrown trying to cheat balance");
       }
       catch(error){
           done();
       }
   });
});

當我使用truffle test執行它時,出現以下錯誤:

 1) Contract: erc20 deployed
      should not transfer 1 token from address[0] to address[1]:
    Uncaught Error: VM Exception while processing transaction: revert

我怎麼能抓住它?我的目標是測試傳遞函式,測試那個地址

$$ 0 $$無法有效地進行交易。

試試這個:

contract('erc20 deployed', function(accounts) {
   const REVERT = "VM Exception while processing transaction: revert";
   it("should not transfer 1 token from address[0] to address[1]", async function() {
       try {
           await erc20Instance.transfer(accounts[1], 1);
           throw null;
       }
       catch (error) {
           assert(error, "Expected an error but did not get one");
           assert(error.message.startsWith(REVERT), "Expected '" + REVERT + "' but got '" + error.message + "' instead");
       }
   });
});

作為 goodvibration 答案的替代方案,也可以使用我的truffle-assertions庫,其中包括一個輔助函式來斷言合約函式恢復。

可以通過npm安裝

npm install truffle-assertions

接下來,可以在測試文件的頂部導入它

const truffleAssert = require('truffle-assertions');

然後它可以在你的測試中使用:

contract('erc20 deployed', function(accounts) {
   it("should not transfer 1 token from address[0] to address[1]", async function() {
       await truffleAssert.reverts(erc20Instance.transfer(accounts[1], 1), null, "No error was thrown trying to cheat balance");
   });
});

完整的文件可以在 GitHub 上找到

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