【问题标题】:clojure test case assertion failure for isclojure 测试用例断言失败是
【发布时间】:2016-10-08 07:53:06
【问题描述】:

我的源代码中有一个简单的函数hello

(defn hello [n] (str "Hello" n))

在测试用例中,我调用了hello 函数。但似乎它正在返回nil。测试用例:

(deftest test    (testing "string"
    ;(is (= "Hello x" (ql/hello "x")))))
    (is (= (ql/hello "x") "Hello x"))))

我收到以下错误。

expected: (= (ql/hello "x") "Hello x")
  actual: (not (= nil "Hello x"))

为什么返回nil?如果我从 repl 调用 hello 函数,我会得到“Hello x”,然后是 nil,但我认为这是由于 repl 造成的,对吧?当我从另一个函数调用hello 时,它不应该返回字符串吗?我直接从 repl 运行测试用例,而不是使用 lein。

【问题讨论】:

  • 我在repl中没有得到nil

标签: unit-testing clojure assertions


【解决方案1】:

从您的描述看来,您实际的 hello 函数定义为:

(defn hello [n]
  (println "Hello" n))

当您运行(hello "x") 时,它会将Hello x 打印到控制台并返回nil(这是println 的行为)。

要让您的测试通过,您需要在 REPL 中重新定义您的函数,以便它与您的版本匹配 str 而不是 println

boot.user=> (require '[clojure.test :refer :all])
nil
boot.user=> (defn hello [n]
       #_=>   (println "Hello" n))
#'boot.user/hello
boot.user=> (is (= "Hello x" (hello "x")))
Hello x

FAIL in () (boot.user5664236129068656247.clj:1)
expected: (= "Hello x" (hello "x"))
  actual: (not (= "Hello x" nil))
false
boot.user=> (defn hello [n]
       #_=>   (str "Hello " n))
#'boot.user/hello
boot.user=> (is (= "Hello x" (hello "x")))
true
boot.user=> 

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    相关资源
    最近更新 更多