Search code examples
unit-testingclojureassertions

clojure test case assertion failure for is


I have a simple function hello in my source.

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

In the test case I am calling the hello function. But seems like it is returning nil. Test case:

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

I am getting the following error.

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

Why is it returning nil? If I call the hello function from repl I get "Hello x" followed by nil, but I think it is due to repl right? When I call hello from another function, shouldn't it return the string? I am running the test case from repl directly and not using lein.


Solution

  • From your description it seems that your actual hello function was defined as:

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

    When you run (hello "x") it prints Hello x to the console and returns nil (that's the behaviour of println).

    To get your test passing you need to redefine your function in the REPL so it matches your version with str instead of 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=>