gpt4 book ai didi

unit-testing - Clojure - 使用组件策略进行测试

转载 作者:行者123 更新时间:2023-11-28 19:50:35 24 4
gpt4 key购买 nike

我正在使用 Stuart Sierra 组件实现一个应用程序。正如他在 README 中所说:

Having a coherent way to set up and tear down all the state associated with an application enables rapid development cycles without restarting the JVM. It can also make unit tests faster and more independent, since the cost of creating and starting a system is low enough that every test can create a new instance of the system.

这里的首选策略是什么?类似于 JUnit oneTimeSetUp/oneTimeTearDown 的东西,或者真的在每个测试之间(类似于 setUp/tearDown)?

如果在每次测试之间,是否有一种简单的方法可以为所有 测试(之前和之后)启动/停止系统,而无需每次都重复代码?

编辑:显示我的意思的示例代码

(defn test-component-lifecycle [f]
(println "Setting up test-system")
(let [s (system/new-test-system)]
(f s) ;; I cannot pass an argument here ( https://github.com/clojure/clojure/blob/master/src/clj/clojure/test.clj#L718 ), so how can I pass a system in parameters of a test ?
(println "Stopping test-system")
(component/stop s)))

(use-fixtures :once test-component-lifecycle)

注意:我在这里谈论的是单元测试。

最佳答案

我会编写一个宏,它采用系统映射并在运行测试之前启动所有组件并在测试之后停止所有组件。

例如:

(ns de.hh.new-test
(:require [clojure.test :refer :all]
[com.stuartsierra.component :as component]))


;;; Macro to start and stop component
(defmacro with-started-components [bindings & body]
`(let [~(bindings 0) (component/start ~(bindings 1))]
(try
(let* ~(destructure (vec (drop 2 bindings)))
~@body)
(catch Exception e1#)
(finally
(component/stop ~(bindings 0))))))

;; Test Component
(defprotocol Action
(do-it [self]))

(defrecord TestComponent [state]
component/Lifecycle
(start [self]
(println "====> start")
(assoc self :state (atom state)))
(stop [self]
(println "====> stop"))

Action
(do-it [self]
(println "====> do action")
@(:state self)))

;: TEST
(deftest ^:focused component-test
(with-started-components
[system (component/system-map :test-component (->TestComponent"startup-state"))
test-component (:test-component system)]

(is (= "startup-state" (do-it test-component)))))

运行测试你应该看到这样的输出

====> start
====> do action
====> stop

Ran 1 tests containing 1 assertions.
0 failures, 0 errors.

关于unit-testing - Clojure - 使用组件策略进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com