Clojure - deftype ignored - unable to resolve classname on tests

最后都变了- 提交于 2019-12-12 14:13:55

问题


I'm testing deftype and defprotocol in Clojure, but I'm in a bit of a pickle.

I'm using leiningen. My core file (src/core.clj) looks like this:

(defprotocol Speaker
  (say [speaker message]))

(deftype Person [name]
  Speaker
  (say [_ message] (str name ": " message)))

My test file (test/core.clj) looks like this:

(deftest people-can-talk
  (is (= "Peter: hello" (say (Person. "Peter") "hello"))))

When I execute that test (with lein test) I get the following error:

Exception in thread "main" java.lang.IllegalArgumentException: Unable to resolve classname: Person, compiling:(my-project/test/core.clj:2)
at clojure.lang.Compiler.analyzeSeq(Compiler.java:6416)
at clojure.lang.Compiler.analyze(Compiler.java:6216)

I believe it is telling me that Person isn't defined. But it is! If it wasn't, wouldn't Clojure have thrown an error? Is there some obvious syntax error I'm missing?

I'm using clojure 1.3.0 .


回答1:


To use classes defined by deftype in another package/file, you need to (import) them, or provide the full package name, like (core.Person. "Peter") - or whatever the namespace for core.clj is.

Additionally, "lein test" only loads the test files. If you want to refer to anything in another file, you'd need to use or require that file in the test file.




回答2:


You suggestion did not resolve the class reference error for me. But implementing a "factory method" as described below is a work-around: another stackoverflow answer on this issue



来源:https://stackoverflow.com/questions/8201933/clojure-deftype-ignored-unable-to-resolve-classname-on-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!