Truffle Testing – Accessing Testrpc Addresses from Solidity Tests

contract-developmenttestingtestrpctruffle

I'm consulting truffle's docs on how to test contracts directly in solidity.

http://truffleframework.com/docs/getting_started/solidity-tests

I'd like to figure out a way to refer to existing testrpc accounts in my tests. Something like:

pragma solidity ^0.4.11;

import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/BAToken.sol";

contract TestBAToken {
  function testNewBATokenNotFinalized() {
    address companyFundAddress = addresses[1];  // <-- I'd like this to be a predefined testrpc account
    address userFundAddress = addresses[2];
    uint256 startBlock = block.number - 100;
    uint256 endBlock = block.number + 100;
    BAToken ba = new BAToken(companyFundAddress, userFundAddress, startBlock, endBlock);
    Assert.equal(ba.isFinalized, false, "Token sale shouldn't be finalized upon initialization.");
  }
}

Is this possible? If not, anyone have any good recommendations for how to refer to existing accounts during testing?

Best Answer

You can directly add the addresses in the solidity contract instead of addresses[1] and addresses[2]. If you do not want to do that, then you can declare some variables in the contract for the addresses and intialize them as part of the constructor as shown below.

contract TestBAToken {
  address companyFundAddress;
  address userFundAddress;
  function TestBAToken(address address1, address address2) {
    companyFundAddress = address1;
    userFundAddress = address2;
  }
  function testNewBATokenNotFinalized() {
    uint256 startBlock = block.number - 100;
    uint256 endBlock = block.number + 100;
    BAToken ba = new BAToken(companyFundAddress, userFundAddress, startBlock, endBlock);
    Assert.equal(ba.isFinalized, false, "Token sale shouldn't be finalized upon initialization.");
  }
}

If you want the declare the addresses inside that function only rather than the complete contract. You can pass them as arguments for testNewBATokenNotFinalized function.

The way to implement depends on how you would like the contract to be and what it should do.

Related Topic