尝试在 clojure 中为方法 arugment 类型检查添加单元测试时出错

Got an error when try to add unit tests for method arugment type checking in clojure

提问人:Laodao 提问时间:11/8/2023 更新时间:11/15/2023 访问量:69

问:

我是clojure的新手,下面是我的代码

(ns my.class.package
    (:require [clojure.tools.logging :as log]
              [schema.core :as s]))

(s/defn my-method :- CandidateInfo [candidates :- [CandidateInfo] goal :- Goal]
  (doseq [candiate candidates]
    (s/validate CandidateInfo candidate))
  (s/validate Goal goal)
  ......)

我做的单元测试是

(testing "test bad input schema"
           (let [candidates [{:bad-attr1 "123" :bad-attr2 "456"}]
                 goal {:id "123" }]
             (is (thrown? ExceptionInfo
                          (try
                            (my-class/my-method candidates goal)
                            (catch ExceptionInfo e
                              (throw e)))))))

我得到的错误是

ERROR in (test-my-method) (core.clj:155)
Uncaught exception, not in assertion.
expected: nil
  actual: clojure.lang.ExceptionInfo: Value does not match schema: {:id missing-required-key, :name missing-required-key}
at schema.core$validator$fn__14239.invoke (core.clj:155)
    schema.core$validate.invokeStatic (core.clj:164)
    schema.core$validate.invoke (core.clj:159)
    my.class.package.my-class$eval32123$my_method__32128$fn__32129.invoke (my-class.clj:36)
......

我的理解是,我确实期望在我的单元测试中抛出一个 ExceptionInfo。但是,错误一直说我期望为零。请帮忙!!

单元测试 Clojure

评论


答:

0赞 akond 11/8/2023 #1

尝试:

(require '[schema.test :as st])

(st/deftest SchemaTest
    (testing "test bad input schema"
        (let [candidates [{:bad-attr1 "123" :bad-attr2 "456"}]
              goal       {:id "123"}]
            (is (thrown? ExceptionInfo
                    (try
                        (my-class/my-method candidates goal)
                        (catch ExceptionInfo e
                            (throw e))))))))

评论

0赞 Laodao 11/8/2023
感谢您的回复,@akond。所以你建议确保deftest是schema.test中的那个?我确实试了一下。没有运气,还是同样的错误。
1赞 akond 11/8/2023
在这种情况下,我需要一个最小的工作可重现代码来调查它。
0赞 user2609980 11/15/2023 #2

如果你的代码实际上抛出了一个 this works:ExceptionInfo

(defn my-method [_ _]
  (throw (ex-info "help!" {}))) ; intentionally throw ExceptionInfo

(deftest bad-input-schema-test
  (testing "test bad input schema"
    (let [candidates [{:bad-attr1 "123" :bad-attr2 "456"}]
          goal {:id "123"}]
      (is (thrown? clojure.lang.ExceptionInfo (my-method candidates goal))))))

你不需要尝试捕捉和重新投掷,尽管它也有效。

也许你的代码没有抛出?

我假设schema.test在命名空间中使用clojure.test:

(:require
 [clojure.test :refer [deftest testing is]])