Foundry test: How to Write Basic Tests

This commit is contained in:
David E. Perez Negron R 2023-08-20 00:57:02 -06:00
parent 3208f88328
commit fe866cb658
2 changed files with 32 additions and 14 deletions

View File

@ -1,14 +1,22 @@
// SPDX-License-Identifier: UNLICENSED // SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13; pragma solidity ^0.8.20;
contract Counter { contract Counter {
uint256 public number; uint public count;
function setNumber(uint256 newNumber) public { // Funcion to get the current count
number = newNumber; function get() public view returns (uint) {
return count;
} }
function increment() public { // Function to increment count by 1
number++; function inc() public {
count += 1;
}
// Function to decrement count by 1
function dec() public {
// thid function will fail if count = 0
count -= 1;
} }
} }

View File

@ -1,7 +1,7 @@
// SPDX-License-Identifier: UNLICENSED // SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13; pragma solidity ^0.8.13;
import {Test, console2} from "forge-std/Test.sol"; import {Test, stdError} from "forge-std/Test.sol";
import {Counter} from "../src/Counter.sol"; import {Counter} from "../src/Counter.sol";
contract CounterTest is Test { contract CounterTest is Test {
@ -9,16 +9,26 @@ contract CounterTest is Test {
function setUp() public { function setUp() public {
counter = new Counter(); counter = new Counter();
counter.setNumber(0);
} }
function testIncrement() public { function testInc() public {
counter.increment(); counter.inc();
assertEq(counter.number(), 1); assertEq(counter.count(), 1);
} }
function testSetNumber(uint256 x) public { function testFailDec() public {
counter.setNumber(x); counter.dec();
assertEq(counter.number(), x); }
function testDecUnderFlow() public {
vm.expectRevert(stdError.arithmeticError);
counter.dec();
}
function testDec() public {
counter.inc();
counter.inc();
counter.dec();
assertEq(counter.count(), 1);
} }
} }