2

Tryng out some smalltalk + TDD + "good practices" I've run into a kinda ugly block:

How do I do an assertion in GNU Smalltalk?

I'm just looking for a simple ifFalse: [Die] kind of thing

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
Tordek
  • 10,628
  • 3
  • 36
  • 67

4 Answers4

2

This is the code for assert: from Squeak (which I recommend you use rather than GNU):

assert: aBlock 
    "Throw an assertion error if aBlock does not evaluates to true."
    aBlock value
        ifFalse: [AssertionFailure signal: 'Assertion failed']
  • Why would you not recommend the GNU version? – Eyvind Mar 20 '09 at 09:28
  • Lack of support - squeak has a more involved community, plus Squeak is more fun. –  Mar 20 '09 at 09:31
  • More support comes from more people using it. And GNU Smalltalk is actually evolving nicely. There are quite some people behind, with Paolo Bonzini as main force. – Janko Mivšek Mar 20 '09 at 10:02
  • 3
    Dont listen to the die-hard Squeakers, they just haven't seen a file system in years :) You can have fun with any Smalltalk. – akuhn Mar 20 '09 at 13:08
2

as well as self assert: [ ... some block ]

works for blocks & non-blocks, since sending #value to Object returns self.

Igor Stasenko
  • 136
  • 1
  • 2
0

It is simple. In your test methods you write:

self assert: 1 + 1 = 2

But first you need to create a test class as a subclass of TestCase (in Squeak), for example:

TestCase subclass: #MyTest

Here you write testing methods, which names must always start with 'test', for instance :

testBasicArithmetics

self assert: 1 + 1 = 2
Janko Mivšek
  • 3,954
  • 3
  • 23
  • 29
  • Plainly doing that reports that "Matrix does not understand #assert:". – Tordek Mar 20 '09 at 20:39
  • Yes, you need to make a test class of course and put assertions in test methods there. See my update. – Janko Mivšek Mar 22 '09 at 09:48
  • 1
    Sorry, it was a misunderstanding: I don't mean unit-test assertions, but design-by-contract assertions. (IE, pre/post-condition checking within the method.) – Tordek Mar 22 '09 at 21:54
0

It has been suggested above to add #assert: to Object, but rather I'd add #assert to BlockClosure (or whatever [] class is in GNU Smalltalk).

assert
    this value ifFalse: [AssertionFailure signal: 'Assertion failed']

and thus use as in

[ value notNil ] assert.
[ value > 0 ] assert.
[ list isEmpty not ] assert.

etcetera.

akuhn
  • 27,477
  • 2
  • 76
  • 91
  • Why not a method on booleans? `(value > 0) surely.` I guess because the test might produce a non-boolean or an exception, though it doesn't seem like the Smalltalk way to worry much about that. – Darius Bacon Feb 16 '13 at 01:33