Here's some code (as babel source blocks in an Org mode file, but you can extract them and run them in an Elisp file instead) - I hope it's self-explanatory, but I have to post-and-run, so I will add some verbiage later on.
* Code :noexport:
Define the function to test:
#+name: my-func
#+begin_src elisp
(defun my-func (file)
(if (not (file-exists-p file))
(display-warning 'my-func-file-not-found file)
;; else file exists: do something with it - here I just return the string "yes"
"yes"))
#+end_src
#+RESULTS: my-func
: my-func
Write the test:
#+name: my-func-test
#+begin_src elisp
(require 'ert)
(defun check-for-warning (msg)
(with-current-buffer "*Warnings*"
(goto-char (point-min))
(search-forward msg nil t)))
(ert-deftest test-my-func/warning-produced ()
"Call my-func with non-existent file and check that the warning is produced."
(let ((fname "/some/non/existent/path"))
;;; This (killing a buffer) is something that tests are *NOT* supposed to do,
;;; but I can't think of a clean way to *test* a side-effect producing function like `display-warning'.
;; if the *Warnings* buffer exists, kill it.
(condition-case x
(kill-buffer "*Warnings*")
('error t))
;; run the function to test
(my-func fname)
;; check that the side-effect has happened
(should (check-for-warning (format "Warning (my-func-file-not-found): %s" fname)))))
#+end_src
Run the test:
#+name: run-tests
#+begin_src elisp
(ert "test-my-func/")
#+end_src
(my-func "path/to/no/file")
how do I test for this with ERT ?