s LearnSqueak.com

PRACTICAL SQUEAK WORKSHOP

SUnit: make a test fail, then make it pass

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.

Classes and objects · Using Squeak’s tools

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.

01 · Define the smallest cart and its first test

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
Object subclass: #LSCart
	instanceVariableNames: 'prices'
	classVariableNames: ''
	poolDictionaries: ''
	category: 'LearnSqueak-Testing'!

!LSCart methodsFor: 'initialization'!
initialize
	super initialize.
	prices := OrderedCollection new
! !

!LSCart methodsFor: 'accessing'!
totalCents
	^ 1
! !

TestCase subclass: #LSCartTest
	instanceVariableNames: 'cart'
	classVariableNames: ''
	poolDictionaries: ''
	category: 'LearnSqueak-Testing'!

!LSCartTest methodsFor: 'running'!
setUp
	super setUp.
	cart := LSCart new
! !

!LSCartTest methodsFor: 'tests'!
testEmptyCartTotalsZero
	self assert: cart totalCents equals: 0
! !

Expected result

LSCart and LSCartTest exist. The test compiles. We have not claimed that it passes.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
1. Define the smallest cart and its first test in native Squeak 6.1
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
2. Run it and understand the failure in native Squeak 6.1
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
totalCents
    ^ prices inject: 0 into: [:sum :price | sum + price]
Expected result

The same test now passes: 1 run, 1 pass, 0 failures, 0 errors.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
3. Change the implementation, keep the assertion in native Squeak 6.1
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
4. Repeat the same test after every change in native Squeak 6.1
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.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
5. Add prices and give every test a fresh fixture in native Squeak 6.1
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
testRejectsNegativePriceWithoutChangingCart
    cart addPrice: 250.
    self should: [cart addPrice: -1] raise: Error.
    self assert: cart totalCents equals: 250.
    self assert: cart itemCount equals: 1
Expected result

The invalid operation is rejected; the test passes, with 250 cents and one item still present.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
6. Test an expected error and unchanged state in native Squeak 6.1
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.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
7. Make a view fixture and clean it up in native Squeak 6.1
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
testAddButtonUsesModel
    view addButton doButtonAction.
    self assert: cart totalCents equals: 250.
    self assert: view totalText equals: '1 items / 250 cents'
Expected result

5 view tests pass. Together with the 6 model tests, the final lesson suite has 11 passes.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
8. Test the button’s effect, not its pixels in native Squeak 6.1
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
9. Run both test classes together in native Squeak 6.1
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
10. Try the same behavior in Morphic in native Squeak 6.1
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
TestCase subclass: #LSCartDiagnosticTest
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'LearnSqueak-Testing'!

!LSCartDiagnosticTest methodsFor: 'tests'!
testFailureExample
	self assert: 1 equals: 2
! !

!LSCartDiagnosticTest methodsFor: 'tests'!
testErrorExample
	Object new cartTotalThatDoesNotExist
! !

Expected result

Exactly 2 run: 1 deliberate failure and 1 deliberate error. This is not the final green suite.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
11. Tell a failed assertion from an unexpected exception in native Squeak 6.1
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.
Expected result

14 run, 14 passes, 0 failures, 0 errors.

Download this checkpoint source

NATIVE SQUEAK CAPTURE
12. Finish with tested extensions in native Squeak 6.1
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
SUnit: make a test fail, then make it pass demonstration
Scripted native TestRunner sequence. The failing assertion is yellow in Squeak 6.1; the fixed result is green.
NATIVE SQUEAK CAPTURE
SUnit: make a test fail, then make it pass demonstration
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.

Browser → LSCartTest → tests-exercises

Write the test first
testRemoveLastHandlesEmptyCart
    self assert: cart removeLast isNil.
    cart addPrice: 250; addPrice: 175.
    self assert: cart removeLast equals: 175.
    self assert: cart totalCents equals: 250
Show a tested solution

System Browser → LSCart → instance side → changing → accept removeLast

Exercise solution
removeLast
    prices ifEmpty: [^ nil].
    ^ prices removeLast
Expected

The removed price is 175 and the remaining total is 250. Empty removal answers nil.

Download complete exercise solution

2. 2. Ask whether the cart is empty

Introduce isEmpty on the model. Cover the new, filled, and cleared states without reading the prices instance variable from the test.

Browser → LSCartTest → tests-exercises

Write the test first
testIsEmptyTracksClear
    self assert: cart isEmpty.
    cart addPrice: 250.
    self deny: cart isEmpty.
    cart clear.
    self assert: cart isEmpty
Show a tested solution

System Browser → LSCart → instance side → accessing → accept isEmpty

Exercise solution
isEmpty
    ^ prices isEmpty
Expected

The boolean changes true → false → true.

Download complete exercise solution

3. 3. Add a different price through the view

Introduce addPrice: on the view. It must update the model and the visible text, using the existing refresh method.

Browser → LSCartViewTest → tests-exercises

Write the test first
testAddsAnotherPriceThroughView
    view addPrice: 175.
    self assert: cart totalCents equals: 175.
    self assert: view totalText equals: '1 items / 175 cents'
Show a tested solution

System Browser → LSCartView → instance side → actions → accept addPrice:

Exercise solution
addPrice: cents
    cart addPrice: cents.
    self refresh
Expected

One item, 175 cents, and a matching visible label. All 14 model/view tests pass.

Download complete exercise solution

When something looks wrong

The runner shows no tests.

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.

    Explore more working examples · Return to the learning path