我写了一个非常简单的合约:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Add {
uint sum = 0;
address public manager;
constructor() {
manager = msg.sender;
}
function add(uint num) public restricted returns (uint) {
sum += num;
return sum;
}
modifier restricted() {
require (msg.sender == manager, "Can only be executed by the manager");
_;
}
}
然后,我使用这个插件进行单元测试,代码也很简单:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// This import is automatically injected by Remix
import "remix_tests.sol";
// This import is required to use custom transaction context
// Although it may fail compilation in ’Solidity Compiler ’ plugin
// But it will work fine in ’Solidity Unit Testing ’ plugin
import "remix_accounts.sol";
import "../contracts/Add.sol";
contract AddTest is Add {
address acc0;
address acc1;
function beforeAll() public {
acc0 = TestsAccounts.getAccount(0);
acc1 = TestsAccounts.getAccount(1);
}
/// #sender: account-0
function managerTest() public {
Assert.equal(manager, acc0, "Manager should be acc0"); // 更新断言错误信息
}
/// #sender: account-0
function addTest() public {
Assert.equal(this.add(2), 2, "You are not Manager!");
}
}
我在这个测试用例中指定了sender=account-0,但我使用this.add方法调用时,会报错:提示不是管理员无法调用。这是为什么呢?
✘ Add test
Error Message:
"transaction reverted with the reason: Can only be executed by the manager"