Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Add Testing ether transactions example #55

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions public/docs/getting_started/solidity-tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,3 +145,41 @@ contract TestContract {
```

Note that Truffle sends Ether to your test contract in a way that does **not** execute a fallback function, so you can still use the fallback function within your Solidity tests for advanced test cases.

Below is another example with ether transactions and parameters. Imagine a crowdfunding campaign contract on which contributors could attach a message to their contribution. Here is an extract of the contract to be tested:

```javascript
eggplantzzz marked this conversation as resolved.
Show resolved Hide resolved
contract Campaign {

// code of campaign smart contract
...

function contribute(string _message) public payable {
amountRaised += msg.value;
// todo store contribution _message in the contributions array
...
}
}
```
Here is the code to test the `payable` function `contribute` with a `string _message` in parameter

```javascript
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```javascript
```solidity

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

contract TestCampaign {
// Truffle will send the TestContract 5 Ether after deploying the contract.
uint public initialBalance = 5 ether;
Campaign campaign = Campaign(DeployedAddresses.Campaign());

// Testing the contribute() function
function testContribute() public {
// Expected contribute increase amountRaised
uint256 expected = 5 ether;
campaign.contribute.value(5 ether) ("my test message");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that the .value syntax doesn't exist anymore in current versions of Solidity. We probably want this to be up to date, so the syntax would be campagain.contribute{value: 5 ether}("my test message").

uint256 amountRaised = campaign.amountRaised();
Assert.equal(amountRaised, expected, "amountRaised of contract should be equal 5.");
}
}
```