-
-
Save quii/82c5aa1472d9e7c730aa1b6353d47c2e to your computer and use it in GitHub Desktop.
(ns tdd-clojure.contract-test | |
(:require [clojure.string :as str] | |
[clojure.test :refer :all])) | |
(defn test-greet-contract [greet-fn] | |
(testing "greet function should return a greeting with the given name" | |
(let [name "Chris"] | |
(is (= (greet-fn name) (str "Hello, " name)))))) | |
;; Example implementation of the greet function | |
(defn greet1 [name] | |
(str "Hello, " name)) | |
;; Another way to do a greet function | |
(defn greet2 [name] | |
(str/join " " ["Hello," name])) | |
;; Greet using fmt | |
(defn greet3 [name] | |
(format "Hello, %s" name)) | |
;; Greet using replace (dumb but fun) | |
(defn greet4 [name] | |
(str/replace "Hello, WAT" #"WAT" name)) | |
;; Test the example implementation using the contract test | |
(test-greet-contract greet1) | |
(test-greet-contract greet2) | |
(test-greet-contract greet3) | |
(test-greet-contract greet4) |
@theronic I guess the point of the "contract" being a separate thing that lives outside of deftest
is that other implementations of it could import the contract to verify themselves. A common use-case for contracts is you may want to have an in-memory store say, and a Postgres one, and you want to verify they both behave how you want.
Use RCF: https://github.com/hyperfiddle/rcf
RCF is async-friendly hotness with :=
syntax, e.g. (greet-fn "Chris") := "Hello, Chris"
. Smarter IDE will hopefully also show test result next to the expression.
Re: contracts, so...interfaces? :) Hmm, I would rather test against a Clojure protocol then (interfaces). I guess tests are usually not easy to generalize once written? But then might as well wrap impl. in interface and update tests?
Also look at Clojure Spec, esp. for generative testing.
Yeah I'm actually looking at specs this morning! https://github.com/quii/learn-clojure-with-tests/blob/5e8bb5ac763c263efe0c4d0cb45aea3b97f145b4/src/learn_clojure_with_tests/specs.clj#L52
@theronic Thanks so much! Much needed experience here