[英]How can I test calling a contract function from a specific address?
Here's my contract:这是我的合同:
// 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);
}
}
Here's my test:这是我的测试:
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");
})
})
})
I would like to test that the lastPoster
field gets updated on the contract to the address that last called the setText
function.我想测试
lastPoster
字段是否在合同上更新为最后调用setText
函数的地址。
What I don't know is how to generate (or fetch) an address that has a balance.我不知道的是如何生成(或获取)具有余额的地址。 I need that to call
setText
from
that specific address, so that I can then assert
that noteDrop.lastPoster()
equals that sender address.我需要
from
该特定地址调用setText
,这样我就可以assert
noteDrop.lastPoster()
等于该发件人地址。
What am I missing?我错过了什么? How can I generate an address to do this?
我怎样才能生成一个地址来做到这一点?
I found the solution quickly.我很快找到了解决方案。 The answer is that the contract test function can take an optional parameter,
accounts
:答案是合约测试函数可以采用可选参数
accounts
:
contract('NoteDrop', (accounts) => {
You can then use this down in your tests like so:然后你可以像这样在你的测试中使用它:
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.