Tonight I just finished writing a nice piece of code. It allows me to create expectations/mock functions. here is an example:
(expect func (1 3) 4)
I started with this as my base line then built my macro for creating a mock function.
‘expect’ is the macro keyword.
‘func’ is the function to be mocked.
‘(1 3)’ is the argument list.
‘4’ is the return value.
Here is the macro with some helper functions:
(defmacro expect (fn-name args ret-val) (let ((arg-list (make-symbols args))) `(defun ,fn-name ,arg-list (let ((expected-args (list ,@args)) (actual-args (list ,@arg-list))) (if (not (equal expected-args actual-args)) (error (format-expectation-errors expected-args actual-args)) ,ret-val))))) (defun format-expectation-errors (expected actual) (format nil “Incorrect Expection Args~% Expected: ~S~% Actual: ~S” expected actual)) (defun make-symbols (args) (loop for a in args collect (gensym))
The hardest part was to try and get the actual and expected args, but I did it with a little bit of cargo-cultism. evaluation occurs at run-time.
This is not a full blown framework it still need to have some type of controller to keep track of the order of expectations, but that will be for another evening.