Truffle

測試 Truffle 中的 Require 語句

  • March 28, 2020

我寫了一個生成鍵值的函式。功能程式碼在這裡

  mapping(string => bool) processedHash;
  mapping(uint   => bool) HashList;

function generateHash(uint256 _mintAmount, string memory _refNumber) onlyWhitelistAdmin whenNotPaused public returns(bool){
   require(processedHash[_refNumber] == false,'This transaction already processed');
   CreateKey memory cK = CreateKey({
   mintAmount:_mintAmount,
   ReferenceNumber:_refNumber});
   uint _Hash = uint(keccak256(abi.encodePacked(cK.mintAmount, cK.ReferenceNumber)));
   require(HashList[_Hash] == false,'This hash already generated.');
   HashList[_Hash] = true;
   processedHash[_refNumber] = true;
   return true;
   }

如果之前通過參考號生成了一個密鑰,則該密鑰不能在那裡生成,因為首先需要必須在函式中執行,然後事務必須恢復。

我也用松露寫了這個測試:


const assertLib = require('truffle-assertions');
...

it('should not generate the hash for same reference number', async()=>{
 actions.generateHash.call(100, '123', {from: accounts[0]});
 await assertLib.reverts(actions.generateHash.call(100, '123', {from: accounts[0]}));

 });  

Truffle 無法擷取 require 語句。松露給我這個輸出

AssertionError: Did not fail

我怎樣才能抓住這個要求聲明?或者我怎樣才能為函式編寫測試?

謝謝你,

   it('should not generate the hash for same reference number', async()=>{
       actions.generateHash.call(100, '123', {from: accounts[0]});
       await assertLib.reverts(actions.generateHash.call(100, '123', {from: 
       accounts[0]}));

    }); 

在上面的測試語句中,您指定generatehash.call() .call用於讀取狀態變數,由於使用**.call**第一次呼叫generateHash沒有進行任何狀態更改,因此第二次呼叫沒有恢復,試試這個.. .

   it('should not generate the hash for same reference number', async()=>{
       const receipt = await actions.generateHash(100, '123', {from: accounts[0]});
       console.log('Receipt: ', receipt); // For your reference
       await assertLib.reverts(actions.generateHash(100, '123', {from: 
       accounts[0]}));

    }); 

在這種情況下,斷言將通過。

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