0Pricing
Blockchain Smart Contracts with Solidity · 강의

Foundry/Hardhat을 활용한 고급 테스트

Foundry 또는 Hardhat과 같은 테스트 프레임워크의 고급 기능을 활용하여 단위 테스트, 통합 테스트, 퍼즈 테스트를 종합적으로 수행합니다.

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

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

Intro to Advanced Testing

Welcome to advanced smart contract testing! As contracts grow in complexity, simple unit tests aren't enough to guarantee robustness.

We need powerful strategies to catch subtle bugs and ensure security. This lesson dives into sophisticated techniques using frameworks like Foundry or Hardhat.

Why Advanced Testing Matters

Basic tests check expected behavior, but what about unexpected inputs or complex interactions? Advanced testing helps with:

  • Edge Cases: Fuzz testing helps find inputs you didn't anticipate.
  • Interactions: Integration tests verify how multiple contracts work together.
  • Security: Advanced methods uncover vulnerabilities before deployment.

These are crucial for building battle-hardened smart contracts.

Foundry: Your Advanced Toolkit

While Hardhat is excellent, for truly advanced Solidity-native testing, Foundry stands out. It's a blazing fast, portable, and modular toolkit for Ethereum application development written in Rust.

Foundry uses Solidity for writing tests, making it very intuitive for smart contract developers.

Unit Testing Deep Dive with Foundry

Unit tests check individual functions in isolation. With Foundry, you write tests directly in Solidity, often inheriting from Test. Let's test a simple counter contract.

Notice how we set up the test environment in setUp() before each test.

pragma solidity ^0.8.0;

import "forge-std/Test.sol";

contract Counter {
    uint public count;

    function increment() public {
        count++;
    }

    function decrement() public {
        require(count > 0, "Count cannot be negative");
        count--;
    }
}

contract CounterTest is Test {
    Counter public counter;

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

    function test_Increment() public {
        counter.increment();
        assertEq(counter.count(), 1, "Count should be 1 after increment");
    }

    function test_Decrement() public {
        counter.increment(); // count is 1
        counter.decrement(); // count is 0
        assertEq(counter.count(), 0, "Count should be 0 after decrement");
    }

    function testFail_DecrementZero() public {
        // This test specifically expects a revert
        counter.decrement();
    }
}

Understanding Integration Testing

Integration tests verify the interactions between multiple smart contracts or between a contract and external services (like oracles). They ensure that different components work harmoniously.

This is crucial because individual contracts might be bug-free, but their combined logic could introduce issues.

Integration Test Example (Foundry)

Let's simulate a scenario where a Token contract interacts with a Vault contract. The vault allows users to deposit and withdraw tokens.

Our integration test will check if tokens are correctly transferred between them and user balances are updated.

pragma solidity ^0.8.0;

import "forge-std/Test.sol";
import "forge-std/console.sol";

contract MyToken {
    mapping(address => uint) public balances;

    constructor() {
        balances[msg.sender] = 1000;
    }

    function transfer(address to, uint amount) public returns (bool) {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        balances[msg.sender] -= amount;
        balances[to] += amount;
        return true;
    }
}

contract Vault {
    MyToken public token;
    mapping(address => uint) public deposits;

    constructor(address _token) {
        token = MyToken(_token);
    }

    function deposit(uint amount) public {
        // Assume token.transferFrom or approval for real world. 
        // Simplified here for demo to show interaction.
        token.transfer(address(this), amount); 
        deposits[msg.sender] += amount;
    }

    function withdraw(uint amount) public {
        require(deposits[msg.sender] >= amount, "Insufficient deposit");
        deposits[msg.sender] -= amount;
        token.transfer(msg.sender, amount); 
    }
}

contract IntegrationTest is Test {
    MyToken public token;
    Vault public vault;

    address public ALICE = makeAddr("alice");

    function setUp() public {
        token = new MyToken();
        vault = new Vault(address(token));

        // Give ALICE some tokens for testing from initial deployer
        vm.startPrank(address(this));
        token.transfer(ALICE, 500); 
        vm.stopPrank();
    }

    function test_AliceDepositsAndWithdraws() public {
        vm.startPrank(ALICE);
        
        uint initialAliceBalance = token.balances(ALICE);
        uint depositAmount = 100;

        // Alice deposits
        token.transfer(address(vault), depositAmount); 
        vault.deposit(depositAmount); 

        assertEq(token.balances(ALICE), initialAliceBalance - depositAmount, "Alice's balance should decrease");
        assertEq(token.balances(address(vault)), depositAmount, "Vault should hold deposit amount");
        assertEq(vault.deposits(ALICE), depositAmount, "Alice's vault deposit should be recorded");

        // Alice withdraws
        vault.withdraw(depositAmount);
        assertEq(token.balances(ALICE), initialAliceBalance, "Alice's balance should be restored");
        assertEq(token.balances(address(vault)), 0, "Vault should be empty");
        assertEq(vault.deposits(ALICE), 0, "Alice's vault deposit should be zero");

        vm.stopPrank();
    }
}

Fuzz Testing: Uncovering Edge Cases

Fuzz testing (or fuzzing) automatically generates random, unexpected inputs to your functions. Instead of you guessing edge cases, the fuzzer tries millions of combinations.

This is incredibly effective for finding vulnerabilities like integer overflows, underflows, or unexpected reverts that manual tests might miss.

Fuzz Testing in Action (Foundry)

With Foundry, fuzzing is built-in. Just add parameters to your test function! Foundry will automatically generate random values for a and b within reasonable ranges.

This helps ensure our functions handle various inputs correctly, especially when checking for unexpected behavior like overflows or underflows.

pragma solidity ^0.8.0;

import "forge-std/Test.sol";

contract Calculator {
    function add(uint a, uint b) public pure returns (uint) {
        return a + b;
    }

    function subtract(uint a, uint b) public pure returns (uint) {
        require(a >= b, "Cannot subtract more than available");
        return a - b;
    }
}

contract FuzzTest is Test {
    Calculator public calculator;

    function setUp() public {
        calculator = new Calculator();
    }

    // Fuzz test for addition: check if a + b >= a (unless overflow)
    function testFuzz_Add(uint a, uint b) public {
        // Note: For real-world, use SafeMath or explicit checks for overflows.
        // This test implicitly relies on default Solidity overflow behavior.
        uint sum = calculator.add(a, b);
        // If no overflow, sum should be >= a
        if (sum < a) {
            // Overflow occurred
            assertTrue(a > type(uint).max - b, "Expected overflow");
        } else {
            assertTrue(sum >= a, "Sum should be greater than or equal to a");
        }
    }

    // Fuzz test for subtraction: ensure result is always <= a
    function testFuzz_Subtract(uint a, uint b) public {
        // Only run if a >= b to avoid expected reverts from 'require'
        vm.assume(a >= b);
        uint result = calculator.subtract(a, b);
        assertTrue(result <= a, "Result should be less than or equal to a");
    }
}

Property-Based Testing (PBT)

Fuzz testing is a powerful form of Property-Based Testing (PBT). Instead of testing specific examples, PBT defines properties (invariants) that should always hold true for your code.

The fuzzer then generates inputs to try and break these properties. This approach leads to more robust and less brittle tests, identifying edge cases you might never think of manually.

Test Your Knowledge

Which of the following statements about advanced smart contract testing techniques are TRUE?

Recap: Advanced Testing

You've explored the world of advanced smart contract testing!

  • We moved beyond basic unit tests to tackle complex scenarios.
  • Foundry provides powerful tools for Solidity-native testing.
  • Unit tests verify individual components.
  • Integration tests ensure multiple contracts work together.
  • Fuzz testing and Property-Based Testing help discover hidden bugs by generating random inputs and verifying invariants.

Mastering these techniques is essential for deploying secure and reliable smart contracts.

자주 묻는 질문

“Foundry/Hardhat을 활용한 고급 테스트” 강의는 무료인가요?

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

“Foundry/Hardhat을 활용한 고급 테스트”에서 뭘 배우나요?

Foundry 또는 Hardhat과 같은 테스트 프레임워크의 고급 기능을 활용하여 단위 테스트, 통합 테스트, 퍼즈 테스트를 종합적으로 수행합니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?

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

“Foundry/Hardhat을 활용한 고급 테스트” 강의는 얼마나 걸리나요?

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

이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?

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

이 강의의 모든 강의

  1. Foundry/Hardhat을 활용한 고급 테스트
  2. 형식 검증 기초
  3. 메인넷 배포 및 모니터링
  4. 퍼징과 불변식 테스트
← Blockchain Smart Contracts with Solidity(으)로 돌아가기