0Pricing
Web3 & DApp Development Fundamentals · Lekcja

Testowanie za pomocą forge

Testy Solidity

Testowanie za pomocą forge to bezpłatna lekcja Web3 & DApp Development Fundamentals na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Web3 & DApp Development Fundamentals, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Web3 & DApp Development Fundamentals zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Tests Are Contracts

In Foundry a test file is a Solidity contract that inherits from Test in the forge-std library. Each public function whose name starts with test is run as an individual test case.

Test files live in test/ and conventionally use the .t.sol suffix.

import {Test} from "forge-std/Test.sol";

contract CounterTest is Test {
    function testInitialZero() public {
        // ...
    }
}

The setUp Function

The special setUp() function runs before every test, giving each test a fresh, isolated state. Deploy your contracts and seed any fixtures here.

Because state resets between tests, one test can never accidentally depend on another.

Counter counter;

function setUp() public {
    counter = new Counter();
}

Assertions

forge-std provides assertion helpers that fail the test with a clear message when they do not hold:

  • assertEq(a, b) — equality
  • assertTrue(cond) / assertFalse(cond)
  • assertGt, assertLt, assertGe, assertLe
function testIncrement() public {
    counter.increment();
    assertEq(counter.number(), 1);
}

Running Tests

Run the whole suite with forge test. Filter by name with --match-test or by contract with --match-contract. Increase verbosity with -v flags to see logs and traces.

$ forge test
$ forge test --match-test testIncrement -vvv

Expecting Reverts

Use vm.expectRevert immediately before a call that should fail. The test passes only if the next call reverts, optionally matching a specific error message or custom error.

function testOnlyOwner() public {
    vm.prank(address(0xBEEF));
    vm.expectRevert("not owner");
    counter.adminReset();
}

Impersonating Accounts

vm.prank(addr) sets msg.sender for the very next call. vm.startPrank(addr) applies it to all calls until vm.stopPrank(). This lets you test access control without deploying from many keys.

vm.startPrank(alice);
token.approve(spender, 100);
token.transfer(bob, 50);
vm.stopPrank();

Manipulating Balances and Time

Cheatcodes let you control the environment:

  • vm.deal(addr, amount) — set an account's ETH balance
  • vm.warp(timestamp) — set block.timestamp
  • vm.roll(blockNum) — set block.number

These make time-dependent and balance-dependent logic easy to test deterministically.

vm.deal(alice, 10 ether);
vm.warp(block.timestamp + 7 days);
vm.roll(block.number + 100);

Testing Events

vm.expectEmit declares which event fields to check, followed by the expected event, then the call that should emit it. The booleans select which topics and data to match.

vm.expectEmit(true, true, false, true);
emit Transfer(alice, bob, 100);
token.transfer(bob, 100);

Labels and Logs

vm.label(addr, name) gives addresses readable names in traces. console.log from forge-std prints debug output during tests when run with sufficient verbosity.

import {console} from "forge-std/console.sol";

vm.label(alice, "Alice");
console.log("balance:", token.balanceOf(alice));

Fork Testing

Foundry can fork a live network so your tests run against real deployed contracts and state. Set an RPC URL and use vm.createSelectFork to pin a block.

This is invaluable for testing integrations with protocols like Uniswap or Aave without redeploying them.

function setUp() public {
    vm.createSelectFork(vm.rpcUrl("mainnet"), 19000000);
}

Test Organization

Good practices for forge tests:

  • One behavior per test function
  • Descriptive names like testRevertWhenNotOwner
  • Shared setup in setUp()
  • Use prank for access control, warp for time logic
  • Add fork tests for external integrations

Quick Check

What is the purpose of the setUp() function in a Foundry test contract?

Recap

You learned forge testing:

  • Tests are Solidity contracts inheriting Test; functions start with test
  • setUp() gives fresh state per test
  • Assertions: assertEq, assertTrue, etc.
  • Cheatcodes: prank, deal, warp, expectRevert, expectEmit
  • Fork tests run against live network state

Next: fuzzing and invariant testing.

Często zadawane pytania

Czy lekcja „Testowanie za pomocą forge” jest bezpłatna?

Tak — pełny tekst „Testowanie za pomocą forge” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Web3 & DApp Development Fundamentals, przejdź na CoddyKit PRO. Kurs Web3 & DApp Development Fundamentals zawiera 4 lekcji w sumie.

Co nauczysz się w „Testowanie za pomocą forge”?

Testy Solidity Ćwiczysz Web3 & DApp Development Fundamentals z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Web3 & DApp Development Fundamentals?

Nie wymagamy żadnego doświadczenia. Web3 & DApp Development Fundamentals w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Testowanie za pomocą forge”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Web3 & DApp Development Fundamentals?

Tak. Każda lekcja Web3 & DApp Development Fundamentals zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Foundry a Hardhat
  2. Testowanie za pomocą forge
  3. Fuzzing i niezmienniki
  4. cast i anvil
← Powrót do Web3 & DApp Development Fundamentals