街区建筑商!我在测试合同中的返回值时遇到了困难,因为返回uint值总是一个“事务”对象(实际上我不知道这意味着什么)。
Here是我正在做的事情的全貌:
我试图创建一个银行合同,允许客户注册进入银行,进行存款和提取存款。为了检查客户是否真的注册成功,我给新注册的客户添加了5醚。
我首先在await中使用TestContracts.js和async来避免嵌套回调,但是测试失败了,因为返回值是transaction object而不是uint。
然后,我采用了一种使用promise.then的不同方法。但是,这更奇怪,因为根本没有调用assert函数,所以测试总是通过给定的任何期望值。
Implementation of Bank合同:
contract Bank {
struct Customer {
address _address; // address of customer
uint deposit;
}
address owner;
mapping(address => Customer) public customerList;
uint customerCounter;
constructor() public payable {
require(msg.value == 30 ether, "Initial funding of 30 ether required for rewards");
/* Set the owner to the creator of this contract */
owner = msg.sender;
customerCounter = 0;
}
function enroll() public returns(uint){
customerList[msg.sender].deposit = 5;
customerList[msg.sender]._address = msg.sender;
customerCounter++;
return customerList[msg.sender].deposit;
}Implementation of TestContracts.js 使用 async 和 await
contract("Test", function(accounts) {
console.log("total accounts: ",accounts);
const alice = accounts[1];
const bob = accounts[2];
const charlie = accounts[3];
it("add 1 people to the bank", async ()=>{
const bank = await Bank.deployed();
const aliceBalance = await bank.enroll({from:alice});
assert.equal(aliceBalance, 5, "initial balance is incorrect");
})Implementation of TestContracts.js 使用 Promise
contract("Test", function(accounts) {
console.log("total accounts: ",accounts);
const alice = accounts[1];
const bob = accounts[2];
const charlie = accounts[3];
it("add 1 people to the bank", function(){
Bank.deployed().then(function(bank){
return bank.enroll({from:alice})
}).then(function(balance){
assert.equal(aliceBalance, 0, "initial balance is incorrect");
});
// const aliceBalance = await bank.enroll({from:alice});
})发布于 2018-12-31 16:16:37
您无法从事务中获取返回数据。它不包含在tx收据中,这就是调用enroll()返回tx对象而不是数据的原因。如果要获取它返回的数据,则必须使用await bank.enroll.call({from:alice})进行调用,而不是事务。当然,这实际上不会改变任何状态变量。
https://ethereum.stackexchange.com/questions/64844
复制相似问题