You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对返回多值映射的Solidity函数进行单元测试?

测试返回多值的Solidity映射读取函数

你的问题出在对Solidity多返回值函数的调用处理上——每次调用getData都会返回一个包含三个元素的数组,而你把整个数组分别赋值给了三个变量,导致后续的断言完全不匹配。

正确的测试逻辑

  1. 单次调用getData获取完整的返回值集合
  2. 从返回结果中拆分出对应的姓名、邮箱、金额三个字段
  3. 分别对每个字段做断言验证

修正后的测试代码

it("The mappings should be empty", async function () {
    const idNumber = "";
    // 一次调用拿到所有返回值,解构为三个独立变量
    const [currentName, currentEmail, currentAmount] = await dataStorage.getData(idNumber);

    const expectedName = "";
    const expectedEmail = "";
    const expectedAmount = 0;

    assert.equal(expectedName, currentName);
    assert.equal(expectedEmail, currentEmail);
    // Solidity的uint256在JS中会返回BigNumber,需转字符串或数字后断言
    assert.equal(expectedAmount.toString(), currentAmount.toString());
});

补充说明

  • Solidity中未赋值的映射会返回对应类型的默认值:字符串默认是空串,uint256默认是0,和你的预期完全匹配
  • 如果使用Waffle/Chai断言库,也可以用更适配BigNumber的写法:expect(currentAmount).to.equal(BigNumber.from(0))

内容的提问来源于stack exchange,提问作者pacelliv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:03:24