@gnosis.pm/mock-contract

中文文档
4.0.0发布于 2020/08/04ISCCommonJS零依赖近 30 天下载 4.7万

在松露测试中模拟依赖合同的简单团结合同.

中文使用文档
文档目录7 节
  1. 模拟一般互动
  2. 个别地模仿方法
  3. 混合方法和参数
  4. 模拟失败
  5. 检查请求
  6. 重设 mock
  7. 复杂 return 类型

Build Status

模拟合同

在松露测试中模拟依赖性的简单团结合同. 它能让你

  • 使依赖性合同返回不同方法和论据的预定义值
  • 模拟例外情况,例如 revert 财务报告和审定财务报表 outOfGas
  • 确定依赖性在多大程度上被称为

模拟合同 允许所有这一切,而无需每次单独写一份测试合同.

在项目中使用

从 npm 安装模块

npm i -D @gnosis.pm/mock-contract

允许汇编 MockContact

  • 添加新内容 Imports.sol 页:1 contracts 文件夹工程
  • 将以下代码复制到 Imports.sol数字 :
pragma solidity ^0.6.0;

// We import the contract so truffle compiles it, and we have the ABI 
// available when working from truffle console.
import "@gnosis.pm/mock-contract/contracts/MockContract.sol";
  • 在 Javascript 单位测试中使用 :
const MockContract = artifacts.require("./MockContract.sol")

// Instantiate mock and make it return true for any invocation
const mock = await MockContract.new()
await mock.givenAnyReturnBool(true)

// instantiate "object under test" with mocked contract.
const contractToTest = await ComplextContract.new(mock.address)

逐个步骤示例

我们假设我们想测试以下智能合同,它执行一个简单的招标程序:

pragma solidity ^0.6.0;
import "./Token.sol";

/**
 * Contract that stores the highest bidder while securing payment from a given ERC20 Token.
 * Upon each bid the cost of bidding is incremented.
 */
contract SimpleAuction {
  address public captor; // Address of the highest bidder
  
  Token private token;
  uint256 private cost;

  constructor(Token _token) public {
    token = _token;
  }

  function bid() public {
    if (token.transferFrom(msg.sender, this, cost + 1)) {
      require(token.transfer(captor, cost), "Refund failed");
      captor = msg.sender;
      cost += 1;
    }
  }
}

如果我们要为这个班级编写单位测试,我们就必须提供一份ERC20令牌合同的执行. 通常有两种处理方式:

  1. 使用真实的 ERC20 令牌合同,并配置为测试工作(例如调用) token.approve (投标前)
  2. 执行假托肯合同,而不是真正的逻辑包含假执行(例如. return true 给一切)

1)的问题是,使我们的依赖性以预期方式行事所需的逻辑可能非常复杂并需要额外的维修工作. 它也不隔离我们的测试 - 而不是仅仅测试测试的单元 它正在测试多个组件的整合.

解决方案 2 需要写入 假话 每种依赖的合同。 这需要时间,污染了寄存器和迁移文件,并带有许多非生产代码.

模拟一般互动

模拟合同 可作为任何类型合同的通用假物品。 我们可以告诉我们的嘲弄,它应该回到某些理由。 例如,假设我们想写一个测试案例,其中ERC20转移工作很好:

const MockContract = artifacts.require("./MockContract.sol")
const SimpleAuction = artifacts.require("./SimpleAuction.sol")
...
it('updates the captor', async () => {
  const mock = await MockContract.new()
  const auction = await SimpleAuction.new(mock.address)

  const trueEncoded = web3.eth.abi.encodeParameter("bool", true)
  await mock.givenAnyReturnBool(trueEncoded)
  await auction.bid({from: accounts[0]})
  
  assert.equal(accounts[0], await auction.captor.call())
})

特别是 await mock.givenAnyReturnBool(true) 以模拟的方式返回 true 任何方法的引用.

一个毫无期望的平庸的嘲弄会回来 无效 默认值(例如). false 对于布尔, 0 (原始内容存档于2018-09-26). for uint等.

其他类型如: givenAnyReturnAddress 或者说 givenAnyReturnUint。可以找到完整的模拟界面 这里。 。 。 .

个别地模仿方法

现在假设我们想测试一下 如果 token.transfer 已经成功,但是 token.transferFrom 失败 :

const Token = artifacts.require("./Token.sol")
...
it('should fail if we fail to refund', async () => {
  const mock = await MockContract.new()
  const auction = await SimpleAuction.new(mock.address)
  const token = await Token.new();

  const transferFrom = token.contract.methods.transferFrom(0, 0, 0).encodeABI() // arguments don't matter
  const transfer = token.contract.methods.transfer(0,0).encodeABI() // arguments don't matter

  await mock.givenMethodReturnBool(transferFrom, true)
  await mock.givenMethodReturnBool(transfer, false)

  try {
    await auction.bid({from: accounts[1]})
    assert.fail("Should have reverted")
  } catch (e) {}
})

不同的方法有不同的ABI编码. mock.givenMethodReturnBool(bytes, boolean) 将ABI编码的方法Id作为第一个参数,并且只为这种方法替换行为. 构造方法Id有两种方法. 我们建议使用 encodeABI 要求原合同的ABI:

// Arguments do not matter, mock will only extract methodId
const transferFrom = token.contract.transferFrom(0, 0, 0).encodeABI()

我们还可以手动创建,例如:

const transferFrom = web3.sha3("transferFrom(address,address,uint256)").slice(0,10) // first 4 bytes

然而,后一种方法并不安全,如果原始合同上的ABI改变,可能导致出乎意料的测试行为. 第一种做法将给这种情况造成一个描述性多得多的汇编错误.

对于其他返回类型(如:. givenMethoReturnUint) (中文(简体) ).

模拟方法将优先于模拟 任意。 。 。 .

混合方法和参数

我们还可以指定不同的行为 当同一个方法被调用 不同的论点:

it('Keeps the old bidder if the new bidder fails to transfer', async () => {
  ...
  const transferFromA = token.contract.methods.transferFrom(accounts[0], auction.address, 1).encodeABI()
  const transferFromB = token.contract.methods.transferFrom(accounts[1], auction.address, 2).encodeABI()

  await mock.givenCalldataReturnBool(transferFromA, true)
  await mock.givenCalldataReturnBool(transferFromB, false)

  await auction.bid({from: accounts[0]})
  await auction.bid({from: accounts[1]})
      
  assert.equal(accounts[0], await auction.captor.call())
})

这次我们需要提供完整的 calldata我们可以轻易使用原始合同的ABI encodeABI呼叫生成它。 同样,其他返回类型的便利功能也存在(例如:. givenMethoReturnUint) (中文(简体) ).

带有精确调用数据的密闭电话优先使用 方法 模拟和 任意 嘲讽.

模拟失败

我们还可以使用 MockContract。所有方法可供 任意, (中文(简体) ), 方法 财务报告和审定财务报表 调用数据 具体电话:

// Revert upon any invocation on mock without a specific message
await mock.givenAnyRevert()

// Revert upon any invocation of `methodId` with the specific message
await mock.givenMethodRevertWithMessage(methodId, "Some specific message")

// Run out of gas, if mock is called with `calldata`
await mock.givenCalldataRunOutOfGas(calldata)

检查请求

一段时间内,如果在测试中看到依赖性被调用的次数,可能是有益的。 例如,我们不妨断言: transfer 如果 transferFrom 首先失败 :

it('only does the second transfer if the first transfer succeed', async () => {
  ...
  await mock.givenAnyReturnBool(false)
  await auction.bid()

  const transfer = token.contract.methods.transfer(0,0).encodeABI()
  
  const invocationCount = await mock.invocationCountForMethod.call(transfer)
  assert.equal(0, invocationCount)
})

我们可以检查是否完全援引 mock 所有方法合并使用 await invocationCount.call() 并使用 await invocationCountForCalldata.call(calldata)。 。 。 .

重设 mock

在整个测试期间,我们可以推翻现有行为:

await mock.givenAnyReturnBool(true) // will return true from now on
await auction.bid()
await mock.givenAnyReturnBool(false) // will return false from now on
await auction.bid()

注意,以前已说明 方法 财务报告和审定财务报表 调用数据 基于行为不会受到压倒性的影响 任意 模拟行为.

要完全重置所有的行为和明确的引用数 我们可以叫:

await mock.reset()

复杂 return 类型

如果返回最常用类型的方法还不够,我们可以手动将ABI编码为任意的固态类型:

const hello_world = web3.eth.abi.encodeParameter("string", 'Hello World!')
await mock.givenAnyReturn(hello_world);

这是一项正在进行中的工作,反馈意见受到高度赞赏。 请在 GitHub 上打开一个问题并/或提交拉动请求 .

版本与发布记录

@gnosis.pm/mock-contract 共发布 13 个版本,首次发布于 2018/09/04;过去 12 个月发布了 0 个版本。

版本发布日期距今
4.0.0latest2020/08/046 年前
3.0.82019/11/226 年前
3.0.72019/02/017 年前
3.0.62019/01/037 年前
3.0.52018/12/207 年前
3.0.42018/12/067 年前

关于 @gnosis.pm/mock-contract 的常见问题

@gnosis.pm/mock-contract 是什么?

在松露测试中模拟依赖合同的简单团结合同.

如何安装 @gnosis.pm/mock-contract?

在项目目录运行 npm install @gnosis.pm/mock-contract,或使用 pnpm add / yarn add / bun add。

@gnosis.pm/mock-contract 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/gnosis.pm__mock-contract 是否存在。

@gnosis.pm/mock-contract 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@gnosis.pm/mock-contract 可以商用吗?

@gnosis.pm/mock-contract 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gnosis.pm/mock-contract 的下载量有多少?

根据 npm 官方下载统计,@gnosis.pm/mock-contract 在 2026/10/17 – 2026/11/15 这 30 天内被下载 46,662 次,日均约 1,555 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gnosis.pm/mock-contract 还在维护吗?

最新版本 4.0.0 发布于 2020/08/04(6 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/09/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。