简体   繁体   中英

clojure.test unable to resolve symbol from `eval`. Works in REPL and lein run

Please bear with this contrived example but it was the simplest thing I could think of to recreate the issue.

(ns something.core)

(defn call-foo [something & args]
  (let [a-foo (:foo (eval (:quux something)))]
    (apply a-foo args)))

(def Something {
  :foo (fn [& args] args)
  :bar (fn [something] (call-foo something))
})

(defn make-something []
  {:quux 'Something})

Running the following in the REPL or with lein run works well.

(let [subject (make-something)                      
      actual (call-foo subject "hello" "greetings")]
  (println actual))                                 
;;=> (hello greetings)

The problem occurs only during this test and executing lein test :

(ns something.core-test
  (:require [clojure.test :refer :all]
            [something.core :refer :all]))

(deftest a-test
  (let [subject (make-something)
        actual  (call-foo subject "hello" "greetings")]
    (is (= ["hello" "greetings"] actual))))

This throws an error. An example output:

ERROR in (a-test) (Compiler.java:6464)
Uncaught exception, not in assertion.
expected: nil
  actual: clojure.lang.Compiler$CompilerException: java.lang.RuntimeException: Unable to resolve symbol: Something in this context, compiling:(/private/var/folders/0n/c7q7860j34xfc2r1x4q51jrh0000gn/T/form-init9215140948330409114.clj:1:6436)

The line "Unable to resolve symbol: Something in this context" makes me think Something is not in context for some reason while I eval in call-foo . But why is this the case only in the test?

The problem is that eval does not see context. Your 'Something resolves in something.core and something.core-test since you have refered all. It won't resolve from whatever namespace where lein test runs its tests.

To fix the immediate problem change

'Something

to

`Something

so that it is namespace-qualified. The test will then run (and fail), but that's another issue ( println returns nil for one thing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM