Skip to content

Testing api endpoints

Dima edited this page Sep 14, 2017 · 5 revisions

Testing api endpoints

To start a project with tests using Leiningen template compojure-api use the option +my-framework-test. Actually the template compojure-api supports clojure-test and midje:

Example:

lein new compojure-api my-api +clojure-test
lein new compojure-api my-api +midje

Initial Test

After creating the project we get the follow test:

core_test.clj

(ns my-api.core-test
  (:require [cheshire.core :as cheshire]
            [clojure.test :refer :all]
            [my-api.handler :refer :all]
            [ring.mock.request :as mock]))

(defn parse-body [body]
  (cheshire/parse-string (slurp body) true))

(deftest a-test

  (testing "Test GET request to /hello?name={a-name} returns expected response"
    (let [response (app (-> (mock/request :get  "/api/plus?x=1&y=2")))
          body     (parse-body (:body response))]
      (is (= (:status response) 200))
      (is (= (:result body) 3)))))

by default, compojure-api use ring-mock to mock requests.

Testing GET endpoint

(testing "Test GET request to /hello?name={a-name} returns expected response"
  (let [response (app (-> (mock/request :get  "/api/plus?x=1&y=2")))
        body     (parse-body (:body response))]
    (is (= (:status response) 200))
    (is (= (:result body) 3))))

Testing POST endpoint

(testing "Test POST request to /echo returns expected response"
  (let [pizza {:name "Turtle Pizza"
               :description "Pepperoni pizza"
               :size :L
               :origin {
                 :country :FI
                 :city "MyCity"}}
        response (app (-> (mock/request :post "/api/echo")
                          (mock/content-type "application/json")
                          (mock/body  (cheshire/generate-string pizza))))
        body     (parse-body (:body response))]
    (is (= (:status response) 200))
    (is (= body pizza)))))