0
0
Blockchain / Solidityprogramming~5 mins

Writing test cases in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Writing test cases helps check if your blockchain code works correctly. It finds mistakes early so your program runs smoothly.

When you create a new smart contract and want to make sure it behaves as expected.
Before deploying blockchain code to avoid costly errors on the network.
When updating your blockchain program to confirm old features still work.
To verify that transactions and state changes happen correctly.
When collaborating with others to ensure everyone's code works well together.
Syntax
Blockchain / Solidity
describe('ContractName', () => {
  it('should do something expected', async () => {
    // setup code
    // call contract function
    // check results with assertions
  });
});

describe groups related tests together.

it defines a single test case with a clear goal.

Examples
This test checks if the contract can save and return the number 42 correctly.
Blockchain / Solidity
describe('SimpleStorage', () => {
  it('stores and retrieves a value', async () => {
    const storage = await SimpleStorage.deploy();
    await storage.deployed();
    await storage.set(42);
    const result = await storage.get();
    assert.equal(result, 42);
  });
});
This test ensures tokens move properly from one account to another.
Blockchain / Solidity
describe('Token', () => {
  it('transfers tokens between accounts', async () => {
    const token = await Token.deploy();
    await token.deployed();
    await token.transfer(account2, 100);
    const balance = await token.balanceOf(account2);
    assert.equal(balance, 100);
  });
});
Sample Program

This test suite checks a simple Counter contract. It confirms the count starts at zero, can increase, and then decrease correctly.

Blockchain / Solidity
const { expect } = require('chai');
const { ethers } = require('hardhat');

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

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

  it('starts at zero', async function () {
    expect(await counter.getCount()).to.equal(0);
  });

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

  it('decrements the count', async function () {
    await counter.increment();
    await counter.decrement();
    expect(await counter.getCount()).to.equal(0);
  });
});
OutputSuccess
Important Notes

Write clear and simple test names to understand what each test checks.

Run tests often to catch problems early.

Use assertions to compare expected and actual results.

Summary

Test cases help catch errors before deploying blockchain code.

Group tests with describe and write clear goals with it.

Test common actions like storing data, transferring tokens, or changing state.