Search code examples
smalltalkpharosqueak

Checking textual representation of a class in a test?


Lets say I've created a class MyClass in Pharo Smalltalk...

If I in Workspace write:

MyClass new.

and select print-it (Ctrl-P), I get:

A MyClass

With a bit of tinkering with MyClass's printOn: method, I could get a bit more, for example:

A MyClass with value: 5

+++

So comes my question... How can I make a test (instance of TestCase-class) that checks that the textual-representation of MyObject - what I would get if I did "MyObject new" and Print-It - is what it's supposed to be?

How do I get the textual representation so I can check it against a string-constant with what it should be, when I do a self assert: equal: (or something similar) in my test?

For example that after using my cutomized printOn: method, it will look something like

A MyClass with value: 5

Sorry for such a newbie question, but there goes...


Solution

  • To get the textual representation of an object you can send the message printString to the object. For example Object new printString will return you the string 'an Object'.

    To create a test case you should create a subclass of TestCase:

    TestCase subclass: #MyClassTestCase
        instanceVariableNames: ''
        classVariableNames: ''
        package: 'MyTest-Package'
    

    Then a test is a method that begins with test. For example the following test verifies the string representation of Object new:

    testClassRepresentation
       self assert: Object new printString equals: 'an Object'