0Pricing
NestJS Enterprise Backend APIs · 강의

스마트 계약 단위 테스트

Solidity 계약의 정확성, 보안성 및 예상 동작을 보장할 수 있도록 포괄적인 단위 테스트를 작성하는 방법을 배우세요.

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

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

Unit Testing Smart Contracts

Welcome to unit testing for smart contracts! This lesson will guide you through writing effective tests for your Solidity code.

Unit tests are crucial in traditional software development, but they are absolutely vital in the blockchain world due to the immutable nature of smart contracts and the financial value they often secure.

Why Test Smart Contracts?

Unlike regular applications, smart contracts, once deployed, cannot be easily changed. Bugs can lead to significant financial losses or system failures.

  • Immutability: Deployed contracts are permanent.
  • High Stakes: Often manage valuable assets.
  • Security: Protect against vulnerabilities.
  • Reliability: Ensure functions behave as expected.
  • Gas Costs: Bugs can waste user funds.

Thorough testing helps catch issues before deployment.

Introducing Hardhat for Testing

Hardhat is a popular Ethereum development environment that includes a powerful testing framework. It provides a local Ethereum network (Hardhat Network) for fast, isolated testing.

  • Local Network: Deploy and test without real gas fees.
  • Ethers.js Integration: Interact with contracts using a familiar JavaScript library.
  • Debugging: Tools for understanding transaction failures.

We'll use Hardhat to write our unit tests.

Basic Contract for Testing

Let's start with a simple Solidity contract that we'll use for our unit tests. This Counter contract allows us to increment, decrement, and get a count.

Copy and save this as contracts/Counter.sol in your Hardhat project.

pragma solidity ^0.8.0;

contract Counter {
  uint public count;

  constructor() {
    count = 0;
  }

  function increment() public {
    count += 1;
  }

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

  function getCount() public view returns (uint) {
    return count;
  }
}

Setting Up Your Test File

Hardhat expects test files to be in the test/ directory. We'll use Mocha for our test runner and Chai for assertions, both integrated with Hardhat.

  • describe(): Groups related tests.
  • it(): Defines an individual test case.
  • beforeEach(): Runs before each test in a describe block, useful for setup.

Let's create a file named test/Counter.js.

Deploying Your Contract in Tests

Before we can test our contract's functions, we need to deploy it to our local Hardhat network. The beforeEach block is perfect for this, ensuring a fresh deployment for every test.

Try running this test file. It should pass if your contract is correctly set up.

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Counter", function () {
  let counter; // Declare 'counter' to be accessible in all tests

  beforeEach(async function () {
    const CounterFactory = await ethers.getContractFactory("Counter");
    counter = await CounterFactory.deploy();
    await counter.deployed(); // Wait for deployment to be confirmed
  });

  // A simple test to confirm deployment
  it("Should confirm the contract is deployed", async function () {
    expect(counter.address).to.not.be.null;
  });
});

Testing Initial State

The first thing to test is if our contract's initial state is correct. Our Counter contract's count should start at 0.

We use expect() from Chai to make assertions about our contract's behavior. to.equal() checks for equality.

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Counter", function () {
  let counter;

  beforeEach(async function () {
    const CounterFactory = await ethers.getContractFactory("Counter");
    counter = await CounterFactory.deploy();
    await counter.deployed();
  });

  it("Should return the initial count of 0", async function () {
    expect(await counter.getCount()).to.equal(0);
  });

  it("Should confirm the contract is deployed", async function () {
    expect(counter.address).to.not.be.null;
  });
});

Testing State Changes (Increment)

Now let's test a function that changes the contract's state. After calling increment(), we expect the count to increase by one.

Remember that state-changing functions need to be awaited because they involve a transaction on the blockchain.

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Counter", function () {
  let counter;

  beforeEach(async function () {
    const CounterFactory = await ethers.getContractFactory("Counter");
    counter = await CounterFactory.deploy();
    await counter.deployed();
  });

  it("Should return the initial count of 0", async function () {
    expect(await counter.getCount()).to.equal(0);
  });

  it("Should increment the count by 1", async function () {
    await counter.increment();
    expect(await counter.getCount()).to.equal(1);
  });

  it("Should confirm the contract is deployed", async function () {
    expect(counter.address).to.not.be.null;
  });
});

Testing Function Logic (Decrement)

We can also test the decrement() function. For this, we first need to increment the counter to ensure count is greater than zero.

This shows how tests can involve a sequence of operations to reach a desired state before asserting the outcome.

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Counter", function () {
  let counter;

  beforeEach(async function () {
    const CounterFactory = await ethers.getContractFactory("Counter");
    counter = await CounterFactory.deploy();
    await counter.deployed();
  });

  it("Should return the initial count of 0", async function () {
    expect(await counter.getCount()).to.equal(0);
  });

  it("Should increment the count by 1", async function () {
    await counter.increment();
    expect(await counter.getCount()).to.equal(1);
  });

  it("Should decrement the count by 1", async function () {
    await counter.increment(); // First increment to make count > 0
    await counter.decrement();
    expect(await counter.getCount()).to.equal(0);
  });

  it("Should confirm the contract is deployed", async function () {
    expect(counter.address).to.not.be.null;
  });
});

Testing for Expected Reverts

Smart contracts often use require() or revert() to enforce conditions. It's vital to test that these conditions correctly trigger a revert when violated.

Chai's to.be.revertedWith() assertion allows us to check for specific error messages.

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("Counter", function () {
  let counter;

  beforeEach(async function () {
    const CounterFactory = await ethers.getContractFactory("Counter");
    counter = await CounterFactory.deploy();
    await counter.deployed();
  });

  it("Should return the initial count of 0", async function () {
    expect(await counter.getCount()).to.equal(0);
  });

  it("Should increment the count by 1", async function () {
    await counter.increment();
    expect(await counter.getCount()).to.equal(1);
  });

  it("Should decrement the count by 1", async function () {
    await counter.increment();
    await counter.decrement();
    expect(await counter.getCount()).to.equal(0);
  });

  it("Should revert if decrementing from zero", async function () {
    await expect(counter.decrement()).to.be.revertedWith("Count cannot be negative");
  });

  it("Should confirm the contract is deployed", async function () {
    expect(counter.address).to.not.be.null;
  });
});

Quick Check: Test Assertions

What are the key benefits of using expect().to.be.revertedWith("...") in smart contract unit tests?

Recap: Unit Testing Power

In this lesson, you've learned the critical importance of unit testing for smart contracts and how to write effective tests using Hardhat, Mocha, and Chai.

  • Smart contracts require rigorous testing due to their immutability.
  • Hardhat provides a powerful local environment for fast testing.
  • You can test initial states, state changes, function logic, and expected reverts.

Mastering unit testing is a fundamental skill for any secure and reliable DApp developer.

자주 묻는 질문

“스마트 계약 단위 테스트” 강의는 무료인가요?

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

“스마트 계약 단위 테스트”에서 뭘 배우나요?

Solidity 계약의 정확성, 보안성 및 예상 동작을 보장할 수 있도록 포괄적인 단위 테스트를 작성하는 방법을 배우세요. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

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

“스마트 계약 단위 테스트” 강의는 얼마나 걸리나요?

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

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

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

이 강의의 모든 강의

  1. 단위 및 종단 간 테스트
  2. Hardhat 및 Truffle 프레임워크
  3. API 성능 테스트
  4. 스마트 계약 단위 테스트
  5. Docker 컨테이너화와 Kubernetes
  6. 테스트넷 및 메인넷 배포
← NestJS Enterprise Backend APIs(으)로 돌아가기