Bird
Raised Fist0
Blockchain / Solidityprogramming~30 mins

Writing test cases in Blockchain / Solidity - Mini Project: Build & Apply

Choose your learning style10 modes available
Writing Test Cases for a Simple Blockchain
📖 Scenario: You are working on a simple blockchain project. To make sure your blockchain works correctly, you need to write test cases that check its basic functions.
🎯 Goal: Build test cases to verify the blockchain's ability to add blocks and validate the chain.
📋 What You'll Learn
Create a blockchain list with initial data
Set a variable for the expected chain length
Write a test function to check adding a block
Print the test results
💡 Why This Matters
🌍 Real World
Writing test cases helps ensure that blockchain code works correctly before it is used in real applications.
💼 Career
Blockchain developers must write tests to verify their code, which is critical for security and reliability in blockchain projects.
Progress0 / 4 steps
1
Create the initial blockchain data
Create a list called blockchain with these exact dictionaries as blocks: {'index': 1, 'data': 'Genesis Block'} and {'index': 2, 'data': 'Second Block'}
Blockchain / Solidity
Hint

Use a list with two dictionaries exactly as shown.

2
Set the expected chain length
Create a variable called expected_length and set it to 3
Blockchain / Solidity
Hint

Just assign the number 3 to expected_length.

3
Write a test function to add a block
Write a function called test_add_block() that adds a new block {'index': 3, 'data': 'Third Block'} to blockchain and returns len(blockchain) == expected_length
Blockchain / Solidity
Hint

Define the function exactly as named and append the new block inside it.

4
Print the test result
Write a print statement that calls test_add_block() and prints 'Test passed' if it returns true, otherwise prints 'Test failed'
Blockchain / Solidity
Hint

Use an if statement to check the function result and print the correct message.

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