在此部分中,我们将为装运合同编写新的 JavaScript 测试。 我们可以改用 Solidity 来编写测试,但 JavaScript 更为常用。 我们将使用 Truffle 测试智能合同。
首先我们创建一个新的测试文件。
const ShippingStatus= artifacts.require("./Shipping.sol");
contract('Shipping', () => {
it("should return the status Pending", async ()=> {
// Instance of our deployed contract
const instance = await ShippingStatus.deployed();
// Checking the initial status in our contract
const status = await instance.Status();
// Checking if the status is initially Pending as set in the constructor
assert.equal(status, "Pending");
});
it("should return the status Shipped", async ()=> {
// Instance of our deployed contract
const instance = await ShippingStatus.deployed();
// Calling the Shipped() function
await instance.Shipped();
// Checking the initial status in our contract
const status = await instance.Status();
// Checking if the status is Shipped
assert.equal(status, "Shipped");
});
it("should return the status Delivered", async ()=> {
// Instance of our deployed contract
const instance = await ShippingStatus.deployed();
// Calling the Shipped() function
await instance.Delivered();
// Checking the initial status in our contract
const status = await instance.Status();
// Checking if the status is Delivered
assert.equal(status, "Delivered");
});
});
我们将使用 truffle 断言包来测试合同中发送的事件。 通过使用此包,我们可以断言交易过程中发出了事件。
const truffleAssert = require('truffle-assertions');
添加一个测试,以确认事件会返回所需的说明。 将此测试放在文件的最后一个测试之后。 在最后一行的一组右大括号的正前方创建新行,在其中添加此测试。
it('should return correct event description', async()=>{
// Instance of our deployed contract
const instance = await ShippingStatus.deployed();
// Calling the Delivered() function
const delivered = await instance.Delivered();
// Check event description is correct
truffleAssert.eventEmitted(delivered, 'LogNewAlert', (event) =>{
return event.description == 'Your package has arrived';
});
});
.deployed() 函数会返回一个承诺。 因此我们在此函数的前面使用 await,并在测试代码的前面使用 async。 此设置意味着,在部署合同后,直到承诺完成后才能继续进行测试。
此模式常用于测试,因为几乎所有智能合同交易都是异步交易。 由于需要先对交易进行验证或挖掘才能将其添加到区块链账本中,因此它们是异步交易。
总之,应以对合同进行全面测试为目标,尤其是计划部署到主要的 Ethereum 网络(主网)时。
在终端中键入以下内容:
truffle test
应该看到所有测试都成功通过:
输出复制
Contract: HelloBlockchain
testing ResponseMessage of HelloBlockchain
testing Responder of HelloBlockchain
testing RequestMessage of HelloBlockchain
testing State of HelloBlockchain
testing Requestor of HelloBlockchain
testing SendRequest of HelloBlockchain (51ms)
testing SendResponse of HelloBlockchain (46ms)
Contract: Shipping
should return the status Pending
should return the status Shipped (59ms)
should return the status Delivered (58ms)
should return correct event description (39ms)
页面更新:2024-04-23
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号