TheContract.sol
pragma solidity ^0.4.23;
contract TheContract {
struct Object {
address createdBy;
uint balance;
}
Object[] public objects;
mapping (address => uint) countByOwner;
function createNewObject(address _owner, uint _balance) public {
objects.push(Object(_owner, _balance));
countByOwner[_owner]++;
}
function getObjectsCountByOwner(address _owner) external view returns (uint) {
return countByOwner[_owner];
}
function getObjectsByOwner(address _owner) external view returns (uint[]) {
uint[] memory result = new uint[](countByOwner[_owner]);
uint counter = 0;
for (uint i = 0; i < objects.length; i++) {
if (objects[i].createdBy == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
}
theContract.js
var TheContract = artifacts.require('./TheContract.sol');
contract('TheContract', function (accounts) {
const tester = accounts[0];
it('should create new objects by tester', function() {
let theContract;
return TheContract.deployed()
.then((instance) => {
theContract = instance;
return theContract.createNewObject.call(tester, 1)
})
.then(() => {
return theContract.createNewObject.call(tester, 2)
})
.then(() => {
return theContract.getObjectsCountByOwner.call(tester)
})
.then((count) => {
assert.equal(count.toNumber(), 2, 'Object count hasn\'t set properly')
})
})
})
TestTheContract.sol
pragma solidity ^0.4.23;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/TheContract.sol";
contract TestTheContract {
function testCreateNewObject() public {
TheContract theContract = TheContract(DeployedAddresses.TheContract());
address tester = 0x24226C148f9ac4F0B46a9eeD8a426a6D9B9794c3;
theContract.createNewObject(tester, 1);
theContract.createNewObject(tester, 2);
Assert.equal(theContract.getObjectsCountByOwner(tester), 2, "Object count hasn't set properly");
}
}
and then
$ truffle test