0
0
Blockchain / Solidityprogramming~10 mins

Writing test cases in Blockchain / Solidity - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Writing test cases
Identify feature to test
Write test case: inputs, expected output
Run test case
Compare actual vs expected
Confirm code
Repeat
This flow shows how to write and run test cases to check if blockchain code works as expected.
Execution Sample
Blockchain / Solidity
function testTransfer() {
  let balanceBefore = getBalance(user);
  transfer(user, 10);
  let balanceAfter = getBalance(user);
  assert(balanceAfter === balanceBefore - 10);
}
A simple test case checking if transferring 10 tokens reduces user's balance by 10.
Execution Table
StepActionValue/CheckResult
1Get balanceBeforebalanceBefore = 100Stored 100
2Call transfer(user, 10)Balance reduces by 10Transfer done
3Get balanceAfterbalanceAfter = 90Stored 90
4Assert balanceAfter === balanceBefore - 1090 === 100 - 10True, test passes
💡 Test ends after assertion passes confirming transfer works correctly
Variable Tracker
VariableStartAfter Step 1After Step 3Final
balanceBeforeundefined100100100
balanceAfterundefinedundefined9090
Key Moments - 2 Insights
Why do we check balanceBefore before transfer?
We need the original balance to compare after transfer. See execution_table step 1 and 3 where balanceBefore and balanceAfter are stored.
What if the assertion fails?
If assertion fails (step 4), it means transfer did not reduce balance correctly. We must fix code or test before continuing.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is balanceAfter at step 3?
A10
B90
C100
DUndefined
💡 Hint
Check the 'Value/Check' column at step 3 in execution_table
At which step do we confirm the test passes?
AStep 1
BStep 2
CStep 4
DStep 3
💡 Hint
Look at the 'Result' column for the step where assertion is checked
If transfer did not reduce balance, which step would fail?
AStep 4
BStep 1
CStep 2
DStep 3
💡 Hint
Assertion check in step 4 compares expected and actual balances
Concept Snapshot
Writing test cases:
1. Identify feature to test.
2. Write test with inputs and expected output.
3. Run test and capture actual output.
4. Compare actual vs expected.
5. Pass means code works; fail means fix needed.
Repeat for confidence.
Full Transcript
Writing test cases in blockchain means checking if code works as expected. First, pick what to test. Then write a test case with inputs and what you expect to happen. Run the test and get actual results. Compare actual results with expected. If they match, test passes. If not, fix code or test. Repeat this process to make sure your blockchain code is correct and safe.