search
HomeTechnology peripheralsIt IndustryTruffle: Testing Smart Contracts

Truffle: Testing Smart Contracts

Truffle: A powerful tool for efficient automation of smart contract development. This article focuses on smart contract testing.

Smart contract testing is the core link of high-quality smart contract development. Why do we need to pay so much attention to testing? Because smart contracts deal with value, sometimes huge value, this makes them targeted by attackers. You don't want to see your project eventually become a "ghost" in the blockchain cemetery, right?

Key points:

  • Truffle is a must-have tool for automated compilation, testing and deployment of smart contracts, ensuring efficient blockchain development.
  • Because smart contracts handle high-value transactions and are easily targeted, it is crucial to test smart contracts with Truffle.
  • Easy to build a local development test network using ganache-cli (formerly known as TestRPC), which provides pre-loaded Ether coins for cost-effective testing.
  • Truffle supports writing smart contract tests using Solidity and JavaScript, providing flexibility based on developer programming preferences and test complexity.
  • Truffle has a built-in debugger that allows developers to step through code and check variables to solve problems efficiently.

Beginner:

We will create a simple smart contract-based second-hand goods market called HashMarket.

In the terminal, locate the folder where you want to build the project. In this folder, run the following command:

mkdir HashMarket
cd HashMarket
truffle init

You should see output similar to the following:

<code>Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!

Commands:

  Compile:        truffle compile
  Migrate:        truffle migrate
  Test contracts: truffle test</code>

You will also get the file structure as shown below:

<code>.
├── contracts
│   └── Migrations.sol
├── migrations
│   └── 1_initial_migration.js
├── test
├── truffle-config.js
└── truffle.js</code>

For these documents, please refer to the previous article. In short, we have the basic truffle.js files as well as two files for the initial blockchain migration.

Prepare for the test environment

The easiest way to test is to do it on the local network. It is highly recommended to use the ganache-cli (formerly known as TestRPC) tool for contract testing.

Installing ganache-cli (requires Node package manager):

npm install -g ganache-cli
After

, open a separate terminal window or tab and run:

ganache-cli

You should see output similar to the following:

<code>Ganache CLI v6.1.0 (ganache-core: 2.1.0)

... (账户和私钥信息) ...

Listening on localhost:8545</code>

This is a list of all accounts that ganache-cli creates for you. You can use any account you want, but these will preload ether, which makes them very useful (because the test requires ether to pay for gas fees).

After

, go to your truffle.js or truffle-config.js file and add a development network to your configuration:

module.exports = {
    networks: {
      development: {
        host: "127.0.0.1",
        port: 8545,
        network_id: "*"
      }
    }
};

Writing smart contracts

First, we will write a HashMarket smart contract. We will try to keep it simple while retaining the required functionality.

HashMarket is eBay on the blockchain. It allows sellers to publish products and buyers to purchase products using Ether. It also allows sellers to remove the product when it is not sold.

In the contracts folder in the project, create a new file and name it HashMarket.sol. In this file, add the following code: (The same contract code as the original text is omitted here to avoid duplication)

Writing a migration file

You need to write a migration file that lets Truffle know how to deploy your contract to the blockchain. Go to the migrations folder and create a new file named 2_deploy_contracts.js. In this file, add the following code: (The same migration file code as the original text is omitted here to avoid duplication)

Test smart contracts

You can use Solidity or JavaScript to perform smart contract testing. Solidity may be a bit more intuitive when testing smart contracts, but JavaScript offers more possibilities.

Solidity Test

To start the test, in the test folder in the project, create a file named TestHashMarket.sol. (The Solidity test codes that are the same as the original text are omitted here to avoid duplication)

JavaScript Test

Truffle allows us to use JavaScript for testing, leveraging the Mocha test framework. (The same JavaScript test code as the original text is omitted here to avoid duplication)

FAQs (FAQs) about using Truffle to test smart contracts: (The same FAQ section as the original text is omitted here to avoid duplication)

The above is the detailed content of Truffle: Testing Smart Contracts. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Top 21 Developer Newsletters to Subscribe To in 2025Top 21 Developer Newsletters to Subscribe To in 2025Apr 24, 2025 am 08:28 AM

Stay informed about the latest tech trends with these top developer newsletters! This curated list offers something for everyone, from AI enthusiasts to seasoned backend and frontend developers. Choose your favorites and save time searching for rel

Serverless Image Processing Pipeline with AWS ECS and LambdaServerless Image Processing Pipeline with AWS ECS and LambdaApr 18, 2025 am 08:28 AM

This tutorial guides you through building a serverless image processing pipeline using AWS services. We'll create a Next.js frontend deployed on an ECS Fargate cluster, interacting with an API Gateway, Lambda functions, S3 buckets, and DynamoDB. Th

CNCF Arm64 Pilot: Impact and InsightsCNCF Arm64 Pilot: Impact and InsightsApr 15, 2025 am 08:27 AM

This pilot program, a collaboration between the CNCF (Cloud Native Computing Foundation), Ampere Computing, Equinix Metal, and Actuated, streamlines arm64 CI/CD for CNCF GitHub projects. The initiative addresses security concerns and performance lim

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft