【问题标题】:How should I deal with a \n printed by `with-out-str` at the end of the output in a Clojure test?在 Clojure 测试的输出末尾,我应该如何处理由 `with-out-str` 打印的 \n?
【发布时间】:2021-09-01 14:30:17
【问题描述】:

我正在编写一个测试来检查打印到控制台的输出是否与我期望的 JSON 字符串匹配。

(deftest create-account-test
  (testing "Create account"
    (is (= (str (cheshire/generate-string {:account {:active-card true :available-limit 100} :violations []}))
           (with-out-str
             (io/-main "test/sample-input.txt"))))))

测试因不匹配而中断:实际输出末尾的\n

actual: "{\"account\":{\"active-card\":true,\"available-limit\":100},\"violations\":[]}\n"          
diff: - "{\"account\":{\"active-card\":true,\"available-limit\":100},\"violations\":[]}"          
      + "{\"account\":{\"active-card\":true,\"available-limit\":100},\"violations\":[]}\n"

最后我应该如何处理这个换行符?

我考虑将\newline 与预期的字符串连接,但我想有更好的解决方案。

【问题讨论】:

  • 修剪?将换行符添加到预期输出?如果您运行测试的方式影响结果,则在测试中进行补偿。特别是如果它与 SUT 无关(换行符、小打印、键顺序......)
  • 如果测试的目的是检查 JSON 与常规 unordered 映射的等价性,那么简单的字符串比较是有缺陷的。考虑预期的字符串是"{\"a\":0,\"b\":1}",但实际的字符串是"{\"b\":1,\"a\":0}",还是"{\"a\" : 0, \"b\" : 1}"。你认为这是通过还是失败?
  • 为什么你认为预期的字符串不应该包含尾随换行符?

标签: clojure


【解决方案1】:

你可以这样做

(deftest create-account-test
  (testing "Create account"
    (is (= {:account {:active-card true :available-limit 100} :violations []}
           (-> (with-out-str (io/-main "test/sample-input.txt"))
               json/read-string))))))

但如果您有充分的理由比较字符串,只需在其中添加一个 \n。

(deftest create-account-test
  (testing "Create account"
    (is (= (str (cheshire/generate-string {:account {:active-card true :available-limit 100} :violations []}) "\n")
           (with-out-str
             (io/-main "test/sample-input.txt"))))))

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多