In this track: Build, test and reason
advanced · 4 MIN READ

Unit tests for a counter

Assert a small operation’s before-and-after behavior.

LET’S PICTURE IT

A scoreboard test checks the starting score and exactly one legal update.

SEE IT FOR YOURSELF
A valid counter call, step by stepStep 1 / 4
A valid counter call, step by stepFunction requestincrement()No argumentsBefore executionstored count0A local teaching example with a defined starting stateIncoming callCheck function dispatchCheck coded conditionsRules passConditions passContinue executionA failed check can revert insteadCalculation0 + 1Result: 1Storage writecount = 1Persists if call succeedsCalculating a local value and storing it are separate stepsPersistent statecount1Later readGetter reports 1No new incrementState, logs and browser display have different roles

This example begins with count zero and a request to call increment(). No real contract is deployed.

Animated local teaching model. No wallet, RPC or live blockchain data. Some labels and hashes are abbreviated for readability.

Deploy fresh state

Create a new PracticeCounter in the local fixture. Record which account deploys it because the constructor makes that account the owner.

Assert the initial condition

The counter should begin at zero. An initial-state assertion distinguishes a bad setup from a later increment failure.

Call from the intended account

As the owner, call increment once and assert count equals one. A second call should produce two rather than resetting the value.

Keep unrelated behavior separate

Authorization, event encoding and overflow boundaries deserve additional focused tests. One successful increment does not establish those properties.

Define the test

deploy as owner
assert count == 0
owner increments → assert count == 1
owner increments → assert count == 2

Test plans are framework-neutral unless labeled as complete Solidity or JavaScript. Use a local test environment and no real funds.

QUICK CHECK · NO PRESSURE

Why assert the initial count before incrementing?

Your progress stays in this browser.
Keep exploring the original referenceethereum.org ↗

Original explanations by EtherTools. Examples are educational and source-linked; this site is independent of the Ethereum Foundation. Our approach.