Solidity
如何測試多個合約?
我創建了一個乙太坊 dapp,它有多個可以相互訪問並在彼此內部使用方法的合約。我想創建一個 Javascript 測試來模擬這個 dapp 的案例。也就是說,我的測試將有多個
msg.sender
地址,我想呼叫多個合約。我的 dapp 要求在一個合約中進行某些狀態更改,然後才能執行另一個合約。這是我要執行的測試程式碼的 MWE:const Contract1 = artifacts.require("./C1.sol"); const Contract2 = artifacts.require("./C2.sol"); // First contract // Do these tests first to modify the state of C1 contract("Contract1", async () => { await it("First test", () => { Contract1.deployed().then(instance => { return some_value_after_operations; }).then(function (result) { assert.equal(result, true); }) }); }) // Second contract // Do these tests after the first tests contract("Contract2", async () => { await it("First test", () => { Contract2.deployed().then(instance => { return some_value_after_operations; }).then(function (result) { assert.equal(result, true); }) }); })
第一個測試應該測試第一個合約,第二組測試然後需要測試第二個合約,因為第一個合約包含在第一個測試期間所做的狀態更改。我嘗試了多種方法來嘗試這樣做,但每種方法都會導致
"before each" hook:
錯誤。我也嘗試過重新安裝松露並使用其他松露版本。如何按照描述編寫案例測試?
編寫測試案例的一種可能方法是這樣的:
const Contract1 = artifacts.require("./C1.sol"); const Contract2 = artifacts.require("./C2.sol"); contract("Test", accounts => { let result; // First contract // Do these tests first to modify the state of C1 it("First test", async () => { const contract1 = await Contract1.deployed(); result = await contract1.doSomething({from: accounts[0]); assert.equal(result, true); }); // Second contract // Do these tests after the first tests and with the result of the first test it("Second test", async () => { const contract2 = await Contract2.deployed(); const combinedResult = await contract2.doSomething(result, {from: accounts[1]); assert.equal(combinedResult, true); }); })