RacketTestingTDDRackUnitQA

Unit Testing with RackUnit | Schema Programming Part 21

3.145 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

Racket takes testing seriously. The standard library rackunit is baked into the language ethos, making it easy to write tests directly alongside your code.

Advertisement

Basic Checks

The simplest test is check-equal?.

#lang racket
(require rackunit)

(define (add x y) (+ x y))

(check-equal? (add 1 1) 2 "Simple math should work")
(check-equal? (add -1 1) 0 "Negative numbers work")

If these pass, nothing happens (silence is golden). If they fail, you get a detailed error report.

Test Cases and Suites

For larger projects, group your checks.

(require rackunit/text-ui)

(define-test-suite math-suite
  (test-case
   "Addition tests"
   (check-equal? (+ 2 2) 4)
   (check-equal? (+ 0 0) 0))
  
  (test-case
   "Multiplication tests"
   (check-equal? (* 2 3) 6)))

(run-tests math-suite)

Testing Exceptions

You can verify that your code errors when it's supposed to!

(check-exn exn:fail? 
           (lambda () (/ 1 0)))

Organizing Tests in Modules

A common pattern is to put tests in a submodule so they don't run when you import the library, only when you run the file directly or use raco test.

(module+ test
  (require rackunit)
  (check-equal? (my-func 10) 100))

Run them with:

raco test my-file.rkt

Advertisement

Summary

RackUnit isn't an addon; it's a core part of the Racket experience. Using module+ test allows you to keep tests close to the code without bloating your production builds.

Quick Quiz

How do you run tests defined in a 'test' submodule from the command line?

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like