0

I have a simple contract with public function, that can receive value and do something based on that value:

pragma solidity >= 0.8.0 < 0.9.0;

contract ContractA {


    uint public boughtItems = 0;
    uint price = 10;
    address []  buyers; 

    function buySomething() public payable {
        require(msg.value >= price, "Sent value is lower"); 
        boughtItems++;
        buyers.push(msg.sender);
    }
}

and in test folder of my Truffle project I have test contract:

pragma solidity >=0.8.0 <0.9.0;

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

contract TestTicketsRoutes {

    ContractA instance;
    

    address account1 = 0xD8Ce37FA3A1A61623705dac5dCb708Bb5eb9a125;

    function beforeAll() public {
        instance = new ContractA();
    }

    function testBuying() public {
        //Here I need to invoke buySomething with specific value from specific address
        instance.buySomething();

        Assert.equal(instance.boughtItems, 1, "Routes amount is not equal");
    }
}

How do I invoke function of ContractA in my TestContractA with passing value and sender?

1 Answer 1

0

First the test contract will need to have some initial balance balance. To achieve that define a public uint named initialBalance with the required amount. For other details read the section Testing ether transactions.

contract TestTicketsRoutes {
    // Truffle will send the TestContract one Ether after deploying the contract.
    uint public initialBalance = 1 ether;

Solidity has a syntax that allows sending ether when invoking a function: foo{value: amount}(param1, param2). Check the solidity documentation.

function testBuying() public {
    // Here I need to invoke buySomething with specific value from specific address
    uint amount = 110;
    instance.buySomething{value: amount}();

    Assert.equal(instance.boughtItems, 1, "Routes amount is not equal");
}

Your Answer

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

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