首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Solidity:模拟函数返回值

Solidity:模拟函数返回值
EN

Ethereum用户
提问于 2022-05-31 07:59:54
回答 1查看 236关注 0票数 0

我正在编写ERC-721协议,但当所有令牌ids都被创建时,我很难编写一个适当的单元测试。

我想测试的函数:

代码语言:javascript
复制
    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()并断言它抛出一个带有正确错误消息的错误。

那么,我的问题是如何模拟函数的返回值?或者还有其他方法来测试这个?

我试过像这样的东西,戴着硬帽子、华夫饼和工作服:

代码语言:javascript
复制
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()时不会抛出错误。

EN

回答 1

Ethereum用户

发布于 2022-06-02 15:50:02

错误在条件require(totalSupply <= MAX_SUPPLY,中。如果totalSupplyMAX_SUPPLY都等于10,000,则该条件将得到满足,并且不会恢复。

解决方案是只在totalSupply严格小于MAX_SUPPLY时允许薄荷:

代码语言:javascript
复制
require(totalSupply < MAX_SUPPLY, "Purchase would exceed max supply");
票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/129264

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档