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])() ) ) {

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

Withdrawal Pattern

  • Doesn't truffle provide you with multiple wallets (addresses) to work with. Commented Sep 18, 2019 at 18:13

1 Answer 1


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);
// do your assert here
// 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.

  • exactly, still searching for a way to do that in Javascript. Commented Mar 3, 2018 at 5:19

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.