0Pricing
Web3 & DApp Development Fundamentals · 강의

forge 테스트

Solidity 테스트

forge 테스트은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web3 & DApp Development Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web3 & DApp Development Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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.

자주 묻는 질문

“forge 테스트” 강의는 무료인가요?

네 — “forge 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.

“forge 테스트”에서 뭘 배우나요?

Solidity 테스트 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“forge 테스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Foundry와 Hardhat 비교
  2. forge 테스트
  3. 퍼징과 불변식
  4. cast와 anvil
← Web3 & DApp Development Fundamentals(으)로 돌아가기