Question Milena Donato · Dec 27, 2017

Unit test - how do you check if a variable is undefined or null?

Hi everyone

I'm new in Cache development language and I'm starting setting up Unit Tests.

How do you check with an Assert whether a certain variable is null or undefined?

The following assert throws an error on the "null": do $$$AssertEquals(myObj, null, "myObj is null")

Thanks a lot for your help and best regards

Milena

Comments

Robert Cemper · Dec 27, 2017

Try ""   instead of null which would be a variable named null

    do $$$AssertEquals(myObj, "", "myObj is null")

or

    set null="" do $$$AssertEquals(myObj, null, "myObj is null")

or to cover undefined as well

     do $$$AssertEquals($GET(myObj), "", "myObj is null")

0
Eduard Lebedyuk  Dec 28, 2017 to Robert Cemper

Also possible to use $$$NULL macro:

do $$$AssertEquals(myObj, $$$NULL, "myObj is null")
0
Robert Cemper  Dec 28, 2017 to Eduard Lebedyuk

I like macros but I'm always careful concerning their public availability.
This has changed to often over recent releases.

0
Vitaliy Serdtsev  Dec 29, 2017 to Robert Cemper

You are right, the macro $$$NULL present only in %sqlMigration.inc and this is not the file that developers often include to its project.
I prefer to use the macro $$$NULLOREF/$$$NULLOID from %occExtent.inc, which is available by default in the class that inherits from %Library.Base, and for routines is enough to include %systemInclude.inc.

0
Vitaliy Serdtsev · Dec 29, 2017

Undefined variable and the variable contains "" (null) is two different situations, e.g. (see $DATA):

kill myObj
write $data(myObj),! ; -> 0
set myObj=$$$NULLOREF
write $data(myObj),! ; -> 1

In your case it would be better to use $IsObject:

kill myObj
write $IsObject(myObj),! ; -> 0
set d=$$$NULLOREF
write $IsObject(myObj),! ; -> 0
set myObj={}
write $IsObject(myObj),! ; -> 1

Accordingly, should be do $$$AssertTrue('$IsObject(myObj), "myObj is null")

0