模拟合同
在松露测试中模拟依赖性的简单团结合同. 它能让你
- 使依赖性合同返回不同方法和论据的预定义值
- 模拟例外情况,例如
revert财务报告和审定财务报表outOfGas - 确定依赖性在多大程度上被称为
模拟合同 允许所有这一切,而无需每次单独写一份测试合同.
在项目中使用
从 npm 安装模块
npm i -D @gnosis.pm/mock-contract
允许汇编 MockContact
- 添加新内容
Imports.sol页:1contracts文件夹工程 - 将以下代码复制到
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令牌合同的执行. 通常有两种处理方式:
- 使用真实的 ERC20 令牌合同,并配置为测试工作(例如调用)
token.approve(投标前) - 执行假托肯合同,而不是真正的逻辑包含假执行(例如.
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 上打开一个问题并/或提交拉动请求 .