Smalltalk and Assertions

孤人 提交于 2019-12-07 22:53:18

问题


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


来源:https://stackoverflow.com/questions/665455/smalltalk-and-assertions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!