【问题标题】:Testing static routes in compojure在 compojure 中测试静态路由
【发布时间】:2013-12-21 01:03:01
【问题描述】:

我正在尝试为 compojure 静态内容路由编写测试。 我正在通过直接检查响铃响应来测试路由。

一个最小的工作示例如下:

;; src/testing-webapps.core.clj
(ns testing-webapps.core
  (:use [compojure.core]
        [compojure.route   :as route]))

(defroutes web-app
   (route/resources "/")
   (route/not-found "404"))


;; test/testing-webapps.core_test.clj
(ns testing-webapps.core-test
  (:require [clojure.test :refer :all]
            [testing-webapps.core :refer :all]))

(defn request [resource web-app & params]
  (web-app {:request-method :get :uri resource :params (first params)}))

(deftest test-routes
  (is (= 404 (:status (request "/flubber" web-app))))
  (is (= "404" (:body (request "/flubber" web-app))))
  (is (= 200 (:status (request "/test.txt" web-app)))))

测试 404 路由工作正常,但调用 (request "/test.txt" web-app) 会导致 ring.middleware.file-info/not-modified-since? 中出现意外的 NullPointerException

这是堆栈跟踪的顶部:

ERROR in (test-routes) (file_info.clj:27)
Uncaught exception, not in assertion.
expected: nil
  actual: java.lang.NullPointerException: null
 at ring.middleware.file_info$not_modified_since_QMARK_.invoke (file_info.clj:27)
    ring.middleware.file_info$file_info_response.doInvoke (file_info.clj:44)
    clojure.lang.RestFn.invoke (RestFn.java:442)
    ring.middleware.file_info$wrap_file_info$fn__917.invoke (file_info.clj:64)
    [...]

静态路由在浏览器中可以正常工作,但在通过我的request 函数调用时却不行。

是否有更简单的方法可以在 compojure 中测试静态路由?为什么在使用我自己的请求映射调用静态路由时会收到 NullPointerException?

【问题讨论】:

    标签: testing clojure compojure


    【解决方案1】:

    查看not-modified-since? 的来源,我认为问题在于您的请求映射中没有标头,因此它会在此表达式上引发 NPE:(headers "if-modified-since")。尝试像这样更改您的 request 方法:

    (defn request [resource web-app & params]
      (web-app {:request-method :get 
                :headers {"content-type" "text/plain"} ; added a header
                :uri resource 
                :params (first params)}))
    

    您也可以考虑使用ring-mock 创建测试请求。它可以让你与这样的东西隔绝一点。

    【讨论】:

    • 感谢您提供指向 ring-mock 的指针。它看起来非常像一个有用的工具。
    猜你喜欢
    • 2012-05-31
    • 2011-04-23
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2014-03-25
    相关资源
    最近更新 更多