我正在尝试为 Solidity 合约编写一些单元测试。我有一些函数可以根据提供的参数恢复自定义错误。
function dissmissRegulator(address _regulatorAddress) public {
if (msg.sender != s_regulators[msg.sender].regulatorAddress) {
revert EMR__OnlyRegulatorsCanAddOrRemoveRegulators();
}
if (s_regulators[_regulatorAddress].regulatorAddress != _regulatorAddress) {
revert EMR__RegulatorDoesNotExist();
}
delete s_regulators[_regulatorAddress];
}
一开始这看起来很简单,我只需要使用 to.be.revertedWithCustomError 即可。
所以我把这个写在我的单元测试文件中
it("something", async function () {
expect(await emr.dissmissRegulator(regulator))
.to.be.revertedWithCustomError(emr,"EMR__RegulatorDoesNotExist");
});
我预计这个测试会通过,应该不会很复杂。
但事实并非如此。奇怪的是控制台写出这个输出:
Error: VM Exception while processing transaction: reverted with custom error 'EMR__RegulatorDoesNotExist()'
at EMR.dissmissRegulator (contracts/EMR.sol:81)
现在我很困惑,为什么当测试中的错误字符串与抛出的错误匹配时测试失败。我错过了什么吗?我的逻辑有问题吗?
await expect(emr.dissmissRegulator(regulator))
.to.be.revertedWithCustomError(emr,"EMR__RegulatorDoesNotExist");
我等待错误的表达
天哪,这对我帮助很大。我无法理解为什么测试失败。不过确实考虑转向代工厂。测试/构建合约时这种不断的语法切换真的很耗电