Writing test cases helps check if your blockchain code works correctly. It finds mistakes early so your program runs smoothly.
Writing test cases in Blockchain / Solidity
Introduction
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
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); }); });
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);
});
});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.
Practice
1. What is the main purpose of writing test cases for blockchain smart contracts?
easy
Solution
Step 1: Understand the role of test cases
Test cases are written to check if the code works correctly and to catch mistakes early.Step 2: Relate to blockchain deployment
Since blockchain contracts are hard to change after deployment, testing helps avoid costly errors.Final Answer:
To find and fix errors before deploying the contract -> Option AQuick Check:
Test cases catch errors early = C [OK]
Hint: Test cases catch errors before deployment [OK]
Common Mistakes:
- Thinking tests speed up contract execution
- Believing tests increase gas cost intentionally
- Assuming tests make code longer for no reason
2. Which of the following is the correct syntax to group tests in a blockchain testing framework like Mocha?
easy
Solution
Step 1: Recall common test grouping syntax
In Mocha and similar frameworks,describeis used to group related tests.Step 2: Identify correct function name
Onlydescribeis the standard function for grouping; others are incorrect or do not exist.Final Answer:
describe('Token tests', () => { /* tests */ }) -> Option DQuick Check:
Group tests with describe() = A [OK]
Hint: Use describe() to group tests clearly [OK]
Common Mistakes:
- Using group() instead of describe()
- Confusing it() with describe()
- Inventing non-existent functions like testGroup()
3. Consider this test case snippet for a smart contract function that stores a value:
it('should store the value correctly', async () => {
await contract.store(42);
const result = await contract.retrieve();
assert.equal(result.toNumber(), 42);
});
What will be the output if the contract stores 42 correctly?medium
Solution
Step 1: Analyze the test steps
The test callsstore(42)then retrieves the value and checks if it equals 42.Step 2: Understand assertion behavior
If the contract works correctly,result.toNumber()will be 42, soassert.equalpasses without error.Final Answer:
Test passes with no errors -> Option AQuick Check:
Correct value stored means test passes = A [OK]
Hint: If assert matches expected, test passes [OK]
Common Mistakes:
- Assuming test fails even if values match
- Confusing syntax errors with assertion failures
- Ignoring async/await usage in tests
4. Identify the error in this test case for transferring tokens:
it('should transfer tokens', async () => {
await contract.transfer(receiver, 100);
const balance = await contract.balanceOf(receiver);
assert.equal(balance, 100);
});medium
Solution
Step 1: Check async calls and returns
ThebalanceOflikely returns a BigNumber object, not a plain number.Step 2: Verify assertion correctness
Comparingbalancedirectly to 100 fails because types differ; conversion to number is needed.Final Answer:
Incorrect assertion comparing balance object to number -> Option CQuick Check:
Compare values with matching types = D [OK]
Hint: Convert BigNumber to number before assert [OK]
Common Mistakes:
- Forgetting to convert BigNumber to number
- Assuming balanceOf returns a plain number
- Missing await on async calls
5. You want to write a test case that checks if a smart contract correctly rejects unauthorized users from changing the owner. Which approach is best?
hard
Solution
Step 1: Understand test goal
The test should verify that unauthorized users cannot change ownership.Step 2: Choose test action
CallingchangeOwnerfrom a non-owner account and expecting an error confirms access control works.Step 3: Eliminate wrong options
Testing with owner account or no account does not check unauthorized rejection; skipping test misses bugs.Final Answer:
Call the changeOwner function from an unauthorized account and expect an error -> Option BQuick Check:
Test unauthorized access by expecting failure = B [OK]
Hint: Test unauthorized calls expect errors [OK]
Common Mistakes:
- Testing only authorized calls
- Ignoring unauthorized access tests
- Assuming blockchain prevents all unauthorized actions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
