1

How can I test the withdraw() function in a truffle javascript test case for the below contract?

The problem is, If I use the msg.sender from the same contract, the before and after balance will be same.

Is there a way to create a new test contract and use it to call the withdraw function from the javascript test case?

pragma solidity ^0.4.18;

import "./ConvertLib.sol";

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

    event NewDeposit(address _from, uint256 _value);

    function MetaCoin() public {
        balances[tx.origin] = 10000;
    }

    function getBalance(address addr) public view returns(uint) {
        return balances[addr];
    }

    function deposit() payable {
        balances[msg.sender] += msg.value;
        NewDeposit(msg.sender, msg.value);
    }

    function withdraw() {

        if ( ! (msg.sender.call.value(balances[msg.sender])() ) ) {
            throw;
        }

        balances[msg.sender] = 0; // Please don't worry about re-entrancy for now.
    }                   
}

Withdrawal Pattern

0

For your test you can crate a DepositorWithdrawer contract able to call deposit/withdraw from MetaCoin. When the DepositorWithdrawer contract is calling MetaCoin, msg.sender will be the contract address.

The process would look something like this.

MetaCoin mt = new MetaCoin();
DepositorWithdrawer w = new DepositorWithdrawer();
w.transfer(10 ether);
w.deposit(mt);
// do your assert here
w.withdraw(mt);
// do your assert here

Personally, I would prefer doing this as a JavaScript Test. There you have better control about who is sending the transaction and you don't have to code unnecessary contracts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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