繁体   English   中英

如何测试从特定地址调用合约函数?

[英]How can I test calling a contract function from a specific address?

这是我的合同:

// SPDX-License-Identifier: ISC
pragma solidity ^0.8.17;

contract NoteDrop {
    string public text = "Hello, world!";
    address public lastPoster;

    event NewText(
        string text,
        address lastPoster
    );

    constructor() {
        // Do nothing
    }

    function setText(string memory _text) public {
        text = _text;
        lastPoster = msg.sender;
        emit NewText(_text, msg.sender);
    }
}

这是我的测试:

contract('NoteDrop', () => {
  let noteDropContract;

  beforeEach(async() => {
    noteDropContract = await NoteDropContract.new();
  })

  describe('lastPoster', async() => {
    it('is changed automatically', async() => {
      await noteDropContract.setText("something", {from: "XXXXX"});
      const lastPoster = await noteDropContract.lastPoster();
      assert.equal(lastPoster, "XXXXX");
    })
  })
})

我想测试lastPoster字段是否在合同上更新为最后调用setText函数的地址。

我不知道的是如何生成(或获取)具有余额的地址。 我需要from该特定地址调用setText ,这样我就可以assert noteDrop.lastPoster()等于该发件人地址。

我错过了什么? 我怎样才能生成一个地址来做到这一点?

我很快找到了解决方案。 答案是合约测试函数可以采用可选参数accounts

contract('NoteDrop', (accounts) => {

然后你可以像这样在你的测试中使用它:

it('is changed automatically', async() => {
  await noteDropContract.setText("something", {from: accounts[0]});
  const lastPoster = await noteDropContract.lastPoster();
  assert.equal(lastPoster, accounts[0]);
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM