Модульное тестирование смарт-контрактов
Научитесь писать комплексные модульные тесты для контрактов Solidity, чтобы обеспечить их корректность, безопасность и ожидаемое поведение
«Модульное тестирование смарт-контрактов» — бесплатный урок NestJS Enterprise Backend APIs на CoddyKit. Это урок 4 из 6. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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 adescribeblock, 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) и разблокировать остальной курс NestJS Enterprise Backend APIs, подпишись на CoddyKit PRO. Курс NestJS Enterprise Backend APIs содержит 6 уроков всего.
Чему я научусь в уроке «Модульное тестирование смарт-контрактов»?
Научитесь писать комплексные модульные тесты для контрактов Solidity, чтобы обеспечить их корректность, безопасность и ожидаемое поведение Ты практикуешь NestJS Enterprise Backend APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать NestJS Enterprise Backend APIs?
Предыдущий опыт не требуется. NestJS Enterprise Backend APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 6.
Сколько времени занимает урок «Модульное тестирование смарт-контрактов»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке NestJS Enterprise Backend APIs?
Да. Каждый урок NestJS Enterprise Backend APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Модульное и сквозное тестирование
- Фреймворки Hardhat и Truffle
- Тестирование производительности API
- Модульное тестирование смарт-контрактов
- Контейнеризация с Docker и Kubernetes
- Развёртывание в тестовых сетях и основной сети