Smalltalk and Assertions

2019-05-20 08:01发布

问题:

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

回答1:

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']


回答2:

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

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



回答3:

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.



回答4:

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