Bird
Raised Fist0
Blockchain / Solidityprogramming~20 mins

Writing test cases in Blockchain / Solidity - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Blockchain Test Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of a simple smart contract test
Consider this Solidity test snippet using Hardhat framework. What will be the output printed by the test runner?
Blockchain / Solidity
describe('SimpleStorage', function () {
  it('should store and retrieve the value', async function () {
    const SimpleStorage = await ethers.getContractFactory('SimpleStorage');
    const storage = await SimpleStorage.deploy();
    await storage.deployed();

    await storage.store(42);
    const value = await storage.retrieve();
    console.log('Stored value:', value.toString());
  });
});
AStored value: 42
BStored value: 0
CTypeError: value.toString is not a function
DSyntaxError: Unexpected token
Attempts:
2 left
💡 Hint
Remember that retrieve() returns a BigNumber and toString() converts it to a string.
❓ Predict Output
intermediate
1:30remaining
Test case result for failing assertion
What will happen when running this test case in a blockchain test framework?
Blockchain / Solidity
it('should fail when value is incorrect', async function () {
  const value = 10;
  assert.equal(value, 20, 'Value should be 20');
});
ATypeError: assert.equal is not a function
BTest passes silently
CSyntaxError: missing semicolon
DTest fails with message: Value should be 20
Attempts:
2 left
💡 Hint
assert.equal compares two values and throws if they differ.
🔧 Debug
advanced
2:30remaining
Identify the error in this test case
This test case is supposed to check if a transaction reverts. What error will it produce when run?
Blockchain / Solidity
it('should revert on invalid input', async function () {
  await expect(contract.doSomething(0)).to.be.revertedWith('Invalid input');
});
ATest passes successfully
BTypeError: expect(...).to.be.revertedWith is not a function
CSyntaxError: Unexpected token await
DError: contract.doSomething is not a function
Attempts:
2 left
💡 Hint
Check if the testing framework supports the 'revertedWith' matcher.
❓ Predict Output
advanced
3:00remaining
Output of asynchronous test with event listening
What will this test print to the console when run?
Blockchain / Solidity
it('should emit event on action', async function () {
  const tx = await contract.performAction();
  const receipt = await tx.wait();
  const event = receipt.events.find(e => e.event === 'ActionPerformed');
  console.log('Event data:', event.args[0].toString());
});
ATypeError: receipt.events.find is not a function
BEvent data: 123
CEvent data: undefined
DSyntaxError: Unexpected identifier
Attempts:
2 left
💡 Hint
TransactionReceipt in ethers.js has 'logs' property, not 'events'.
🚀 Application
expert
1:30remaining
Number of test cases needed for full coverage
A smart contract function has 3 independent boolean inputs. How many test cases are needed to cover all input combinations?
A3
B6
C8
D9
Attempts:
2 left
💡 Hint
Each boolean can be true or false independently.

Practice

(1/5)
1. What is the main purpose of writing test cases for blockchain smart contracts?
easy
A. To find and fix errors before deploying the contract
B. To make the contract run faster on the blockchain
C. To increase the contract's gas cost
D. To make the contract code longer

Solution

  1. Step 1: Understand the role of test cases

    Test cases are written to check if the code works correctly and to catch mistakes early.
  2. Step 2: Relate to blockchain deployment

    Since blockchain contracts are hard to change after deployment, testing helps avoid costly errors.
  3. Final Answer:

    To find and fix errors before deploying the contract -> Option A
  4. Quick 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
A. itGroup('Token tests', () => { /* tests */ })
B. group('Token tests', () => { /* tests */ })
C. testGroup('Token tests', () => { /* tests */ })
D. describe('Token tests', () => { /* tests */ })

Solution

  1. Step 1: Recall common test grouping syntax

    In Mocha and similar frameworks, describe is used to group related tests.
  2. Step 2: Identify correct function name

    Only describe is the standard function for grouping; others are incorrect or do not exist.
  3. Final Answer:

    describe('Token tests', () => { /* tests */ }) -> Option D
  4. Quick 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
A. Test passes with no errors
B. Test fails with assertion error
C. Syntax error in test code
D. Runtime error due to missing function

Solution

  1. Step 1: Analyze the test steps

    The test calls store(42) then retrieves the value and checks if it equals 42.
  2. Step 2: Understand assertion behavior

    If the contract works correctly, result.toNumber() will be 42, so assert.equal passes without error.
  3. Final Answer:

    Test passes with no errors -> Option A
  4. Quick 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
A. Missing await before balanceOf call
B. No error, test is correct
C. Incorrect assertion comparing balance object to number
D. transfer function called without sender address

Solution

  1. Step 1: Check async calls and returns

    The balanceOf likely returns a BigNumber object, not a plain number.
  2. Step 2: Verify assertion correctness

    Comparing balance directly to 100 fails because types differ; conversion to number is needed.
  3. Final Answer:

    Incorrect assertion comparing balance object to number -> Option C
  4. Quick 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
A. Call the changeOwner function from the owner account and expect success
B. Call the changeOwner function from an unauthorized account and expect an error
C. Call the changeOwner function without any account specified
D. Skip testing unauthorized access because it is handled by blockchain

Solution

  1. Step 1: Understand test goal

    The test should verify that unauthorized users cannot change ownership.
  2. Step 2: Choose test action

    Calling changeOwner from a non-owner account and expecting an error confirms access control works.
  3. Step 3: Eliminate wrong options

    Testing with owner account or no account does not check unauthorized rejection; skipping test misses bugs.
  4. Final Answer:

    Call the changeOwner function from an unauthorized account and expect an error -> Option B
  5. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard