You might have ever written a test for your data conversion logic. E.g.
- Converting data pulled from third-party web service into your internal schema.
- Converting data fetched from your database to more mobile friendly schema before sending out.
This is an example snippet of test for such a scenario.
convert-test1 shows the style I had been writing until recently. convert-test2 shows how using are making the test better.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns demo-are.core-test | |
(:require [clojure.test :refer :all] | |
[demo-are.core :refer [convert]])) | |
(deftest convert-test1 | |
(let [in {:user-name "tap" | |
:email1 "tap@pat.tap" | |
:email2 "pat@tap.pat" | |
:address {:steet "Rama 1"} | |
:latitude "123" | |
:longitude "456"} | |
out {:username "tap" | |
:emails ["tap@pat.tap" "pat@tap.pat"] | |
:address {:street "Rama 1"} | |
:location {:latitude "123" :longitude "456"}}] | |
(is (= (convert in) out)))) | |
(deftest convert-test2 | |
(let [in {:user-name "tap" | |
:email1 "tap@pat.tap" | |
:email2 "pat@tap.pat" | |
:address {:steet "Rama 1"} | |
:latitude "123" | |
:longitude "456"} | |
out (convert in)] | |
(are [x y] (= (get-in in x) (get-in out y)) | |
[:user-name] [:username] | |
[:email1] [:emails 0] | |
[:email2] [:emails 1] | |
[:address :steet] [:address :street] | |
[:latitude] [:location :latitude] | |
[:longitude] [:location :longitude]))) |
convert-test1 shows the style I had been writing until recently. convert-test2 shows how using are making the test better.
Pros:
- No more duplication of field values between input and output.
- No more duplication between output schema and code under test schema.
- It can be use as a document showing clearly how each individual field is mapped.
Cons:
An error message in convert-test1 is better. It shows clearly which field is wrong while convert-test2 throw out the whole problematic result data.
Updated: I have retested, are does report problem for an individual case as well.
No comments:
Post a Comment