Smalltalk and Assertions

2019-05-20 08:02发布

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

4条回答
地球回转人心会变
2楼-- · 2019-05-20 08:09

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

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

查看更多
SAY GOODBYE
3楼-- · 2019-05-20 08:12

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楼-- · 2019-05-20 08:25

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']
查看更多
Juvenile、少年°
5楼-- · 2019-05-20 08:28

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
查看更多
登录 后发表回答