简体   繁体   中英

Why can't I extract with-redefs into a seperate function?

I have a function that I would like to test.

(defn -main
  [& args]
  (let [port (Integer/parseInt (or (first args) "8080"))]
    (run-jetty
      app
      {:port port})))

I need to mock away run-jetty for obvious reasons, so I use with-redefs to verify that the correct args are passed. This works great.

(it "should overide the port with first arg"
        (with-redefs [run-jetty (fn [handler opts] [handler opts])]
            (should= 8081 (jetty-port (underTest/-main "8081")))))

I'd like to extract the with-redefs call since I use it in a few more tests, so I tried this:

(defn mock-jetty
  [test]
  (with-redefs [run-jetty (fn [handler args] [handler args])] test))

(describe "The app"
  (it "should default to port 8080"
      (mock-jetty
        (should= 8080 (jetty-port (underTest/-main))))))

This test calls the real run-jetty function and starts a server. Why does this happen?

EDIT

Changing extraction to a macro:

(defmacro mock-jetty
  [someTest]
  `(with-redefs [run-jetty (fn [handler args] [handler args])] ~someTest))

(describe "The app"
  (it "should default to port 8080"
      (mock-jetty
        (should= 8080 (jetty-port (underTest/-main))))))

throws this exception: Can't use qualified name as parameter: boost-bin.handler-test/handler

I can guess, that it is connected with the fact that with-redefs is a macro. So when you call it straight in code, it executes test body in context of redefs, while when you move it out to the function, the body (should= 8080 (jetty-port (underTest/-main))) is being executed before being passed to macro (as it always happens to functions' params)

To make it work, you could rewrite mock-jetty as a macro:

(defmacro mock-jetty
  [test]
  `(with-redefs [run-jetty (fn [handler# args#] [handler# args#])] ~test))

I'm pretty sure it would help

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