1

How do I test a contract with that has construction parameters? For example what if I had slightly modified the metacoin example contract to include an initial_balance

contract MetaCoin {
  mapping (address => uint) balances;

  function MetaCoin(uint initial_balance) {
    balances[tx.origin] = initial_balance;
  }
  ...

How do I modify the example TestMetacoin.sol

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

contract TestMetacoin {
  function testInitialBalanceUsingDeployedContract() {
    MetaCoin meta = MetaCoin(DeployedAddresses.MetaCoin());

    uint expected = 10000;

    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
  }
  ...

AFAIK the truffle test runner deploys the contracts and the Metacoin(DeployedAddresses.Metacoin()) gets the deployed contract to test. But I don't see any way to pass in the initial_balance to test it.

1 Answer 1

4

There are two solutions.

First solution: change your migrations file and add second parameter here:

deployer.deploy(Contract, initial_balance)

Second solution: just deploy new contract inside your test:

contract TestMetacoin {
  function testInitialBalanceUsingDeployedContract() {
    MetaCoin meta = new MetaCoin(10000);

    uint expected = 10000;

    Assert.equal(meta.getBalance(tx.origin), expected, "Owner should have 10000 MetaCoin initially");
}
1
  • Ahh! That makes a lot of sense. I didn't realize that the truffle test runner uses the migrations to deploy the contracts.
    – mjhm
    Commented Feb 4, 2018 at 3:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.