Build a shopping cart you can change with confidence, then test its Morphic interface.
12 construction stagesTested source & checkpointsNative screenshots & demos
Before you start
A test is an executable example with an expected answer. We will start with one deliberately wrong answer, read the result, and grow a small cart one behavior at a time. Integer cents keep the arithmetic exact. The cart model knows prices; the view knows buttons and labels. The last green checkpoint has 11 tests, and the three exercise solutions extend it to 14.
Work in a learning image and save a copy first. Download and extract this lesson bundle. In Squeak open File List, select the named .st file, and choose fileIn. These files are complete, cumulative checkpoints: start at 01 and move forward. File-in source contains exclamation-mark chunk separators and belongs in File List, not pasted wholesale into a Workspace. Short expressions labeled Workspace can be selected and run with Do It or Print It. A Browser method replaces one method on the named class. No package downloads are required.
The Object subclass declaration creates LSCart with one instance variable, prices. initialize creates a fresh OrderedCollection for each cart. The initial totalCents deliberately returns 1. LSCartTest is a TestCase subclass: SUnit discovers instance methods whose names begin with test. setUp creates the cart that each test will use. The test says what an empty cart should do, independently of how totalCents is implemented. Accepting code only compiles it; it does not run a test.
Where to run this
File List → fileIn source/01-red.st. Then browse LSCartTest → tests → testEmptyCartTotalsZero.
Construction code · follow the run instructions above
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
02 · Run it and understand the failure
Do the expression below, then choose Run Selected in the Test Runner. The expected result is zero; the deliberate implementation produces one. The result is one assertion failure and no errors. Test-driven development often calls this the “red” phase, but Squeak 6.1 displays an assertion-only failure in yellow. Read the counts and the test name rather than relying on a color. A failing test is useful here: it proves the assertion can detect the wrong answer.
Where to run this
Workspace → Do It, then Test Runner → Run Selected.
Construction code · follow the run instructions above
TestRunner openForSuite: LSCartTest suite.
Expected result
1 run, 0 passes, 1 failure, 0 errors. The failure list names testEmptyCartTotalsZero.
NATIVE SQUEAK CAPTURE
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
03 · Change the implementation, keep the assertion
Replace LSCart’s totalCents method with the code below. inject:into: begins with zero and visits each price, passing the accumulated sum and the next price to the block. An empty collection returns the starting value, zero. Do not change the test’s expected zero to make the wrong implementation pass. This version also gives us the summing behavior that the next tests will exercise.
Where to run this
System Browser → LSCart → instance side → totalCents → replace source and Accept. Or fileIn source/02-green.st.
Construction code · follow the run instructions above
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
04 · Repeat the same test after every change
A green result is evidence for the examples actually executed. It does not prove every possible cart behavior. Run Selected again in the existing runner. You can also run a suite without opening a window and inspect its result. The expression below answers a TestResult; Print It shows counts. Keep this feedback loop short: write an example, observe it fail for the intended reason, change the code, rerun.
Where to run this
Workspace → Print It, or the existing Test Runner → Run Selected.
Construction code · follow the run instructions above
LSCartTest suite run.
Expected result
1 run, 1 pass, 0 failures, 0 errors.
NATIVE SQUEAK CAPTURE
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
05 · Add prices and give every test a fresh fixture
File in checkpoint 03. It adds addPrice:, itemCount and clear, plus five more model tests. setUp runs before each test method, so one example’s 250-cent item cannot leak into another example. Never make test order part of the contract. The assertions below check the public behavior: two prices total 425 cents and count as two items. A test of a hard-coded collection layout would make future refactoring harder without protecting the user-facing result.
Where to run this
File List → fileIn source/03-model-tests.st. The displayed methods are on LSCartTest; accept them separately when editing manually.
Construction code · follow the run instructions above
setUp
super setUp.
cart := LSCart new
"Separate method in the tests protocol:"
testAddsPrices
self assert: cart totalCents equals: 0.
cart addPrice: 250.
cart addPrice: 175.
self assert: cart totalCents equals: 425.
self assert: cart itemCount equals: 2
Expected result
6 model tests pass. Empty, multiple-item, zero-price, invalid-price, and clear behavior are exercised.
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
06 · Test an expected error and unchanged state
addPrice: accepts only non-negative integers. A negative price should raise an Error before it modifies prices. should:raise: runs a block and passes only when the expected exception is raised. This expected exception is not a Test Runner error. The two assertions after it matter: rejecting input should leave the existing cart intact. The companion fractional-cents test rejects 1.5. Error is intentionally broad for this small example; a larger domain could introduce a named validation exception.
Where to run this
Browser → LSCartTest → tests → this method. Run LSCartTest suite.
Construction code · follow the run instructions above
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
07 · Make a view fixture and clean it up
File in checkpoint 04. LSCartView wraps a cart, a total label, and two SimpleButtonMorph buttons. The view fixture injects a fresh cart into a fresh view. tearDown deletes that view after each test so open windows do not accumulate. ensure: makes the superclass cleanup run even if our cleanup raises an error. Put allocation and cleanup in the test fixture, not inside an unrelated production method. This example has no files, network connections, or timers to clean up.
Where to run this
File List → fileIn source/04-final.st. The two methods belong separately to LSCartViewTest → running.
Construction code · follow the run instructions above
setUp
super setUp.
cart := LSCart new.
view := LSCartView new model: cart
"Separate method in the running protocol:"
tearDown
[view ifNotNil: [view delete]]
ensure: [super tearDown]
Expected result
The complete fixture creates model and view; tests can open/delete the view without leaving it in World.
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
08 · Test the button’s effect, not its pixels
The add button targets its view and sends addExampleItem. Sending doButtonAction to the button executes that configured target/action, so this test can catch both broken wiring and a missing refresh. It checks the model’s total and the label the user sees. The other view tests cover initial text, Clear, explicitly refreshing after an external model change, and deleting a view from World. These are deterministic component tests; they do not simulate a mouse pointer or prove keyboard navigation and hit-testing work.
Where to run this
Browser → LSCartViewTest → tests. Run LSCartViewTest suite, or fileIn checkpoint 04.
Construction code · follow the run instructions above
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
09 · Run both test classes together
A suite groups examples. Start with the model suite and add the view suite’s individual tests, then open a runner for that combined suite. Run Selected executes both classes. Run the same suite after changing the model, UI actions, or refresh text. Tests should describe observable behavior; changing a label format deliberately means updating that particular expectation, while a change to internal storage should leave these tests alone.
Where to run this
Workspace → Do It, then Test Runner → Run Selected.
Construction code · follow the run instructions above
| suite |
suite := LSCartTest suite.
suite addTests: LSCartViewTest suite tests.
TestRunner openForSuite: suite.
Expected result
11 run, 11 passes, 0 failures, 0 errors.
NATIVE SQUEAK CAPTURE
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
10 · Try the same behavior in Morphic
Open a real view and click Add 250 cents three times. Each button action tells the model to add a price and then asks the view to refresh. Clear empties the model and refreshes the same label. The view has a simple cents display to keep formatting out of the first lesson. Its wording is intentionally stable, including “1 items,” so we can focus on the state transition. You can improve pluralization as a later change with its own examples.
Where to run this
Workspace → Do It. In the new Morphic panel, click Add 250 cents three times, then Clear cart.
Construction code · follow the run instructions above
LSCartView new openInWorld.
Expected result
The label progresses from 0 items / 0 cents to 3 items / 750 cents and returns to 0 items / 0 cents.
NATIVE SQUEAK CAPTURE
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
11 · Tell a failed assertion from an unexpected exception
Optional diagnostic checkpoint 05 installs a separate LSCartDiagnosticTest. One test asserts an intentionally false equality; the other sends an unimplemented selector to Object. Both are deliberate teaching probes. The first appears in Failures; the second appears in Errors because the test cannot reach a meaningful answer. In this image the combined result is red. Compare this with the expected exception in stage 6, which passes. File in checkpoint 04 again, or checkpoint 06, to remove this diagnostic class and return the ordinary lesson category to passing tests.
Where to run this
File List → fileIn source/05-diagnostic-probes.st, then Workspace → TestRunner openForSuite: LSCartDiagnosticTest suite. Run Selected.
Construction code · follow the run instructions above
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
12 · Finish with tested extensions
The final exercise file includes the complete working application and all solutions. It removes the optional diagnostic class. The model now also supports removeLast and isEmpty; the view supports a variable-price action. Run both test classes again. Keep the original examples: new behavior should not silently break empty carts, validation, Clear, or existing buttons.
Where to run this
File List → fileIn source/06-exercise-solutions.st; Workspace → select expression and Print It.
Construction code · follow the run instructions above
| suite |
suite := LSCartTest suite.
suite addTests: LSCartViewTest suite tests.
suite run.
Genuine Squeak 6.1 native capture; this state was prepared by the accompanying script.
Watch the workflow
All pictures are native Squeak 6.1 Morphic, Browser, Workspace, or TestRunner renders. The GIFs are scripted sequences of real native states, not recordings of a person clicking. Button sequences send the button’s own doButtonAction message.
NATIVE SQUEAK CAPTURE
Scripted native TestRunner sequence. The failing assertion is yellow in Squeak 6.1; the fixed result is green.
NATIVE SQUEAK CAPTURE
Scripted native Morphic frames: add 250 cents three times, then Clear. Each state comes from the button’s actual target/action.
Practice with tested solutions
1. 1. Remove the last item safely
Add removeLast. On an empty cart answer nil. Otherwise answer the removed price and reduce the total. Start with the test below, observe the missing behavior, then implement it.
Verify that the class inherits TestCase, its test methods are on the instance side, and each method name begins with test. Reopen the runner after filing in new classes.
I see MessageNotUnderstood for addPrice:.
You are before checkpoint 03 or accepted the method on the wrong class or class side. File in the stated checkpoint and check LSCart → instance.
There are still failures after the optional diagnostics.
File in checkpoint 04 or 06 to remove LSCartDiagnosticTest. The ordinary final suite is LSCartTest plus LSCartViewTest.
The model changes but the text stays the same.
Model changes made outside the view are not automatically observed in this small example. Send view refresh. The explicit-refresh test records that design.
Verification, cleanup and next steps
All file-in methods compiled; Workspace expressions executed; invalid-input state assertions, real button target/action calls, view ownership, and cleanup verified. Pointer/keyboard automation is outside this component-test coverage.
Close the tutorial windows when finished. Save the source separately from the image if you want to recreate the application in a clean image.