간단하게 array를 세팅하는 solidity코드 및 테스트코드 예제입니다. (제가 작성한 건 아니지만..^^)
사전환경: $ganache-cli ( -l 1000000000 -p 7545)
/migrations밑에 2_deploy_contracts.js에 TestArray.sol 추가.
실행방법: $truffle compile -> $truffle migrate -> $truffle test
혹은
$truffle develop
$migrate
$test (test/testarray.test.js)
$truffle network 하면 deploy된 address를 볼 수 있음.
Solidity 소스:
pragma solidity ^0.4.24;
contract TestArray {
uint[] heroArray;
constructor() public {
}
function setHeroArray(uint[] array) public {
for (uint i=0 ; i < array.length; i++) {
setValue(array[i]);
}
}
function setValue(uint a) private {
heroArray.push(a);
}
function getHeroArray(uint a) view public returns(uint[]) {
return heroArray;
}
}
test/testarray.test.js 소스:
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
const json = require('./../build/contracts/TestArray.json');
let accounts;
let arraySC;
const interface = json['abi'];
const bytecode = json['bytecode'];
beforeEach(async() => {
accounts = await web3.eth.getAccounts();
arraySC = await new web3.eth.Contract(interface)
.deploy({data: bytecode})
.send({from: accounts[0], gasLimit: 4000000});
});
describe(' --- Test Array --- ', () => {
it('array Set', async() => {
await arraySC.methods.setHeroArray([3,3,4]).send({from: accounts[0], gasLimit:150000});
let resultArray = await arraySC.methods.getHeroArray(1).call();
console.log('resultArray : ', resultArray);
assert.equal(resultArray[2], 4, "값이 제대로 세팅되지 않았습니다 ");
});
});