如何让REPL识别地图中的测试?

时间:2018-11-21 23:06:50

标签: clojure read-eval-print-loop

我的地图定义如下:

"Arcane Golem"
    {:name        "Arcane Golem"
    :attack      4
    :health      4
    :mana-cost   3
    :type        :minion
    :set         :classic
    :rarity      :rare
    :description "Battlecry: Give your opponent a Mana 
Crystal."
    :battlecry   (fn battlecry [state minion]
                     {:test (fn []
                                (as-> (create-game [{:minions [(create-minion "Arcane Golem" :id "ag")]}]) $
                                      (battlecry $ (get-minion $ "ag"))
                                      (contains? (get-in $[:players "p1" :hand]) "Mana Crystal")))}
                     (-> (get-opponent state (:id minion))
                     (:id)
                     (add-card-to-hand state (create-card "Mana Crystal"))))}

此映射本身是更大的映射图(称为卡定义)中的键/值对。如您所见,我在下面编写了一个关于crycry功能的测试;但是,当我启动REPL并在此地图的名称空间中运行所有测试时,它说Ran 0 tests with 0 assertions.我如何才能获得REPL识别此测试?

1 个答案:

答案 0 :(得分:2)

您可以同时使用with-testdefine a function and a unit test

; with-test is the same as using {:test #((is...)(is...))} in the meta data of the function.

(:use 'clojure.test)

(with-test
    (defn my-function [x y]
      (+ x y))
  (is (= 4 (my-function 2 2)))
  (is (= 7 (my-function 3 4))))

(test #'my-function)            ;(test (var my-function))
=> :ok

注意:使用with-test时,仍必须使用defn将函数定义为全局变量(请参见示例)。测试机器将找不到匿名fn作为映射键的值。

应该起作用的是将函数定义为独立var,然后在映射中包含对它的引用

{:battlecry my-function}    ; for example

已经说过,大多数人(包括我自己)更喜欢拥有一个单独的测试名称空间,以防止测试混乱源代码。我喜欢将它们组织为:

flintstones.core           ; main namespace
tst.flintstones.core       ; the unit test namespace

然后将它们放置在项目目录的./src./test子目录中:

src/flintstones/core.clj            ; main namespace
test/tst/flintstones/core.clj       ; the unit tests

但是还有其他可能性。另请参见the Clojure Cookbook discussion on testing