用redefs进行clojure单元测试

时间:2015-07-01 09:44:35

标签: unit-testing clojure

我有这样的事情:

View v = li.inflate(R.layout.indicator_config, group, false);
LinearLayout r = (LinearLayout) v.findViewById(R.id.configLayout);
Button b = new Button(getContext);
r.addView(b);

单元测试代码

(ns server.core
  (:require [db.api :as d]))

(defrecord Server [host port instance]
  (start [c]
    (let [connection (d/connect (:host c) (:port c))]
      (assoc c :instance connection)))
  (stop [c]
    ;; close the connection
    ))

(defn new-server
  [host port]
  (map->Server {:host host
                :port port}))

使用(ns server.core_test (:require [server.core :refer :all] [clojure.test :refer :all])) (deftest server-test (testing "Calling start should populate :instance" (with-redefs [d/connect (fn [h p] [h p])] (let [server (start (new-server "foobar" 12313123))] (is (-> server :instance nil? not)))))) 运行上面的代码会引发类似于:

的错误

boot watch test

然后我修改测试代码,因此它需要Unable to resolve var: d/connect in this context

db.api

我再次运行测试,这次(ns server.core_test (:require [server.core :refer :all] [clojure.test :refer :all] [db.api :as d])) 仍然引用d/connect

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您需要在测试代码中要求db.api,以便可以访问var d/connect

(ns server.core_test
  (:require [server.core :refer :all]
            [db.api :as d]
            [clojure.test :refer :all]))

(deftest server-test
  (testing "Calling start should populate :instance"
    (with-redefs [d/connect (fn [h p] [h p])]
      (let [server (start (new-server "foobar" 12313123))]
        (is (-> server :instance nil? not))))))