Solidity

用 Solidity 編寫的單元測試,如何更改 msg.sender 地址、msg.value、

  • December 19, 2020

我想知道在編寫單元測試時是否可以更改合約函式呼叫的消息發送者的地址。它真的應該是,我試圖找出如何但不能。

pragma solidity ^0.4.4;

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

contract A {

   event Test(address add);

   function test() {
       Test(msg.sender);
   }
}

contract TestA {

   function test01() {
       A a = A(DeployedAddresses.A());
       a.test(); // <--- msg.sender is address(this), but how do we use a different account from testrpc?
   }
}

在 gitter 中我得到了響應,所以我嘗試像這樣執行它:

a.test({from: 0xf6a948bff792e4f42d7f17e5e4ebe20871d160f2});

它給出了以下錯誤:

TypeError: Wrong argument count for function call: 1 arguments given but expected 0. a.test({from: 0xf6a948bff792e4f42d7f17e5e4ebe20871d160f2});

作業系統:Windows 10 Truffle 版本:v3.4.11 乙太坊客戶端:testrpc v4.1.3 節點版本:v8.7.0 npm 版本:5.4.2

您不能從solidity 中更改發件人地址。可靠性測試在 EVM 內執行,它不允許修改 msg.sender。EVM 的修改版本可能會提供此類功能,但我不知道此類修改。

您可以修改要測試的函式以接受額外的參數,並將所需的發件人傳遞給那裡

contract A {
   // We cannot test directly deposit
   function deposit(uint _amount) public {
       doDeposit(msg.sender, _amount);
   }
   // But we can test doDeposit
   function doDeposit(address _sender) public {
   }
}

contract TestA {
   address constant senderA = "0xA00...";
   address constant senderB = "0xB00...";
   function testDeposit() {
       A a = A(DeployedAddresses.A());
       a.doDeposit(senderA, 10000); 
       a.doDeposit(senderB, 10000); 
   }
}

這並不理想,但它可能有助於發現一些錯誤。

另一種選擇是使用測試合約地址

contract TestA {
   address constant senderA = "0xA00...";
   address constant senderB = "0xB00...";
   function testMint() {
       // TestA is the owner a
       A a = new A(this);
       // Only the owner TestA can mint
       a.mint(senderA, 10000);
       // make senderA approve TestA
       a.doApprove(senderA, this, 1000);
       // testA can make a transfer from senderA
       a.transferFrom(senderA, senderB, 1000);
   }
}

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