我正在编写ERC-721协议,但当所有令牌ids都被创建时,我很难编写一个适当的单元测试。
我想测试的函数:
uint256 public constant MAX_SUPPLY = 10000;
function safeMint() public payable {
uint256 totalSupply = totalSupply();
require(totalSupply <= MAX_SUPPLY, "Purchase would exceed max supply");
//...
}在上面的代码中,我想编写一个单元测试,这样如果总供应量达到了极限,它就会抛出一个错误。
我的第一种方法是模拟totalSupply(),以便返回10,000。然后,我将调用safeMint()并断言它抛出一个带有正确错误消息的错误。
那么,我的问题是如何模拟函数的返回值?或者还有其他方法来测试这个?
我试过像这样的东西,戴着硬帽子、华夫饼和工作服:
describe('MyContract', () => {
describe('given mocked contract', () => {
let mockInstance;
let account;
beforeEach(async () => {
const myContractFactory = await smock.mock('MyContract');
mockInstance = await myContractFactory.deploy();
[account] = await ethers.getSigners();
});
it('given 10,000 tokens ids minted, when safe mint is called, throws', async () => {
await mockInstance.totalSupply.returns(10000);
await expect(
mockInstance.connect(account).safeMint({
value: ethers.utils.parseEther('0.123'),
})
).to.be.revertedWith('Purchase would exceed max supply');
});
});
});上面的代码将总供给设置为10,000,但当调用safeMint()时不会抛出错误。
发布于 2022-06-02 15:50:02
错误在条件require(totalSupply <= MAX_SUPPLY,中。如果totalSupply和MAX_SUPPLY都等于10,000,则该条件将得到满足,并且不会恢复。
解决方案是只在totalSupply严格小于MAX_SUPPLY时允许薄荷:
require(totalSupply < MAX_SUPPLY, "Purchase would exceed max supply");https://ethereum.stackexchange.com/questions/129264
复制相似问题