Elisp: Unit Testing

By Xah Lee. Date: . Last updated: .

Load Unit Testing Lib

there is a unit testing framework bundled with emacs.

(require 'ert)

Define Test

To define a test, use ert-deftest. The syntax is the same as defun

In the body, you should have one or more (should expr). If expr return nil, the test is considered failed.

Sample Test Definition

;; sample unit test
(require 'ert)

;; HHHH------------------------------

;; sample functions to be tested

(defun my-add-1 (N) "add 1" (1+ N) )

(defun my-add-2 (N) "add 2" (+ N 2))

(defun my-string-even (Str)
  "return t if length of str is even, else nil."
  (= (mod (length Str) 2) 0))

(defun my-get-last-char (Str)
  "return the last char of a string"
  (if (> (length Str) 0) (substring Str -1) "" ))

;; HHHH------------------------------

;; sample tests

(ert-deftest xah-test-add ()
  "Test add functions"
  (should (equal (my-add-1 0) 1))
  (should (equal (my-add-1 1) 2))
  (should (equal (my-add-2 1) 3)))

(ert-deftest xah-test-str ()
  "Test string functions"
  (should (my-string-even "aabb"))
  (should (not (my-string-even "a")))
  (should (string-equal (my-get-last-char "abc") "c"))
  (should (string-equal (my-get-last-char "") "")))

eval the code so emacs knows about it. 〔see Emacs: Evaluate Elisp Code

Run Test, Interactively

to run the test interactively, first, eval the test definitions, then,

Alt+x ert Return t Return

elisp unit test 2024-11-11 200242
elisp unit test 2024-11-11 200242

Run Test: Batch

emacs -batch -l ert -l my-test.el -f ert-run-tests-batch-and-exit
elisp unit test batch 2024-05-20
elisp unit test batch 2024-05-20

Reference

Emacs Lisp, Benchmark and Unit Testing