Solidity

無法使用松露測試來測試合約的價值

  • December 31, 2018

塊建設者!我無法測試契約的返回值,因為返回的 uint 值始終是“交易”對象(我實際上並不知道那是什麼意思)

這是我正在做的事情的總體情況:

我嘗試創建一個銀行契約,允許客戶註冊到銀行,進行存款和提取存款。為了檢查客戶端是否真的註冊成功,我給新註冊的客戶端放了 5 個乙太幣。

我首先使用awaitandasyncTestContracts.js避免嵌套回調,但測試失敗,因為返回值是 atransaction object而不是uint

然後,我採用不同的方法使用promise.then. 然而,更奇怪的是,因為assert函式根本沒有被呼叫,所以在給定任何期望值的情況下,測試總是通過。

Bank契約執行:

contract Bank {
struct Customer {
   address _address; // address of customer
   uint deposit;
}

address owner;
mapping(address => Customer) public customerList;
uint customerCounter;

constructor() public payable {
   require(msg.value == 30 ether, "Initial funding of 30 ether required for rewards");
   /* Set the owner to the creator of this contract */
   owner = msg.sender;
   customerCounter = 0;
}

function enroll() public returns(uint){
   customerList[msg.sender].deposit = 5;
   customerList[msg.sender]._address = msg.sender;
   customerCounter++;

   return customerList[msg.sender].deposit;
}

TestContracts.js使用async和實現await

contract("Test", function(accounts) {
console.log("total accounts: ",accounts);
const alice = accounts[1];
const bob = accounts[2];
const charlie = accounts[3];
it("add 1 people to the bank", async ()=>{
   const bank = await Bank.deployed();
   const aliceBalance = await bank.enroll({from:alice});

   assert.equal(aliceBalance, 5, "initial balance is incorrect");
})

TestContracts.js使用的實現Promise

contract("Test", function(accounts) {
console.log("total accounts: ",accounts);
const alice = accounts[1];
const bob = accounts[2];
const charlie = accounts[3];
it("add 1 people to the bank", function(){
   Bank.deployed().then(function(bank){
       return bank.enroll({from:alice})
   }).then(function(balance){
       assert.equal(aliceBalance, 0, "initial balance is incorrect");
   });
   // const aliceBalance = await bank.enroll({from:alice});
})

您無法從交易中獲取返回數據。它不包含在 tx 收據中,這就是呼叫enroll()返回 tx 對象而不是數據的原因。如果要獲取它返回的數據,則必須使用await bank.enroll.call({from:alice}). 然而,這當然不會真正改變任何狀態變數。

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