【发布时间】:2021-07-29 11:58:15
【问题描述】:
我一直在使用Pedestal 进行 RESTful API 服务器及其端点单元测试。这种方法是设置服务器并在端点级别对其进行测试。所谓的“端点单元测试”在下面的页面中有很好的记录。
http://pedestal.io/reference/unit-testing#_testing_your_service_with_response_for
然而,这一次,我将 Lacinia-Pedestal 用于 GraphQL(不是 RESTful,换句话说),我想知道我是否可以应用相同的端点测试逻辑。在 Lacinia-Pedestal 存储库 (https://github.com/walmartlabs/lacinia-pedestal) 中,我找不到相关说明。事实上,它根本没有提到单元测试。
如果有人有这种方法的经验,你能分享一下吗? 谢谢!
-- 编辑 我在这里添加我的测试代码。
resources/main-schema.edn:
{:queries
{:hello
{:type String}}}
core.clj
(ns lacinia-pedestal-lein-clj.core
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[com.walmartlabs.lacinia.pedestal2 :as p2]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.util :as util]
[io.pedestal.http :as http]))
(defn resolve-hello
[_ _ _]
"hello, darren")
(defn hello-schema
[]
(-> (io/resource "main-schema.edn")
slurp
edn/read-string
(util/inject-resolvers {:queries/hello resolve-hello})
schema/compile))
(def service
(-> (hello-schema)
(p2/default-service nil)
http/create-server
http/start))
和Pedestal(不是Lacinia-Pedestal)表示可以通过以下代码sn-p设置和测试服务器实例:
(ns lacinia-pedestal-lein-clj.core-test
(:require [lacinia-pedestal-lein-clj.core :as core]
[clojure.test :as t]
[io.pedestal.http :as http]
[io.pedestal.test :as ptest]
[com.walmartlabs.lacinia.pedestal2 :as p2]
[com.walmartlabs.lacinia.util :as util]))
(def service
(:io.pedestal.http/service-fn
(io.pedestal.http/create-servlet service-map)))
(is (= "Hello!" (:body (response-for service :get "/hello"))))
但是,我相信这种方式适用于 RESTful 但不适用于 GraphQL,因为 GraphQL 需要为服务器设置架构(.edn 文件)和解析器。
所以,我试着调整一下。
(ns lacinia-pedestal-lein-clj.core-test
(:require [lacinia-pedestal-lein-clj.core :as core]
[clojure.test :as t]
[io.pedestal.http :as http]
[io.pedestal.test :as ptest]
[com.walmartlabs.lacinia.pedestal2 :as p2]
[com.walmartlabs.lacinia.util :as util]))
(defonce service
(-> (core/hello-schema)
(p2/default-service nil)
http/create-server
http/start))
(t/is (= "Hello!"
(:body
(util/response-for service
:get "/hello")))) ;; NOT WORKING
但它不能以这种方式工作,因为 response-for 需要 interceptor-service-fn 类型。
所以,据我所知,真正的问题是如何在 GraphQL 服务器实例中使用response-for 函数。
【问题讨论】:
-
如果您在使用 REST 方法时遇到问题并只是切换到 GraphQL,请说明这些问题和相关代码。
-
感谢您的建议,cfrick。我添加了我的测试代码 sn-ps。
-
也许我必须用拦截器包装当前的
service实例。我现在正在尝试。
标签: unit-testing clojure graphql pedestal