Next: How to Organize Tests with Packages, Up: How to Test [Contents][Index]

The most commonly used assertion form is

(assert-equal value form)

This tallies a failure if form returns a value not equal to value. Both value and test are evaluated in the local lexical environment. This means that you can use local variables in tests. In particular, you can write loops that run many tests at once:

> (define-test my-sqrt (dotimes (i 5) (assert-equal i (my-sqrt (* i i))))) MY-SQRT > (defun my-sqrt (n) (/ n 2)) ;; wrong!! > (run-tests my-sqrt) MY-SQRT: (MY-SQRT (* I I)) failed: Expected 1 but saw 1/2 MY-SQRT: (MY-SQRT (* I I)) failed: Expected 3 but saw 9/2 MY-SQRT: (MY-SQRT (* I I)) failed: Expected 4 but saw 8 MY-SQRT: 2 assertions passed, 3 failed.

However, the above output doesn’t tell us for which values of ‘`i`’ the code
failed. Fortunately, you can fix this by adding expressions at the end of the
`assert-equal`

. These expression and their values will be printed on failure.

> (define-test my-sqrt (dotimes (i 5) (assert-equal i (my-sqrt (* i i)) i))) ;; added i at the end MY-SQRT > (run-tests my-sqrt) MY-SQRT: (MY-SQRT (* I I)) failed: Expected 1 but saw 1/2 I => 1 MY-SQRT: (MY-SQRT (* I I)) failed: Expected 3 but saw 9/2 I => 3 MY-SQRT: (MY-SQRT (* I I)) failed: Expected 4 but saw 8 I => 4 MY-SQRT: 2 assertions passed, 3 failed.

The next most useful assertion form is:

(assert-true test)

This tallies a failure if test returns false. Again, if you need to print out extra information, just add expressions after test.

There are also assertion forms to test what code prints, what errors code returns, or what a macro expands into. A complete list of assertion forms is in the reference section.

Do not confuse

`assert-true`

with Common Lisp’s`assert`

macro.`assert`

is used in code to guarantee that some condition is true. If it isn’t, the code halts.`assert`

has options you can use to let a user fix what’s wrong and resume execution. A similar collision of names exists in JUnit and Java.

Next: How to Organize Tests with Packages, Up: How to Test [Contents][Index]