testing - clojure 是否需要依赖注入(inject)来使代码更易于测试?

标签 testing clojure

我记得读过一篇文章,说 Ruby 并不真正需要 DI 或 DI 框架,因为类是开放的。因此,您可以简单地重写依赖项的构造函数,使其返回一个假对象。

我对 Clojure 和函数式编程还很陌生。我想知道 Clojure 是否需要依赖注入(inject)或者它可以出于类似/其他原因放弃它。这是一个具体的示例(请随意指出我的设计如何不符合 Clojure 的惯用方式):

Imagine you're developing a web crawler/spider. It needs to traverse a webpage you've downloaded. This is an action with side-effects. The webpage could change on every query, your internet connection could cut out, etc. It finds all the links on the webpage, visits each one, and then traverses it in the same way.

现在,您想编写一个模拟 http 客户端的测试,以便它返回一个硬编码的字符串响应。如何在测试中调用程序的 -main 并阻止它使用 真实 http 客户端?

最佳答案

clojure.core 中的 with-redefs 宏对于移除函数非常有用。

这里有一个简短的 REPL session 来演示这一点:

user=> (defn crawl [url]
  #_=>   ;; would now make http connection and download content
  #_=>   "data from the cloud")
#'user/crawl
user=> (defn -main [& args]
  #_=>   (crawl "http://www.google.com"))
#'user/-main
user=> (-main)
"data from the cloud"
user=> (with-redefs [crawl (fn [url] "fake data")]
  #_=>   (-main))
"fake data"

由于 Clojure 程序(主要)由函数而非对象组成,因此函数的动态重新绑定(bind)取代了 DI 框架为测试目的所做的大量工作。

关于testing - clojure 是否需要依赖注入(inject)来使代码更易于测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696574/

相关文章:

java - 无法从搜索框中的动态类型中选择值

Clojure : Idiomatic (when (predicate x) x)

clojure - Clojure 中的多态模式验证

Postgresql:日志:启动的 autovacuum 启动器挂起(显然)

clojure - 如何使用 clojure.spec 生成相互关联的参数?

android - 在没有 Java 的情况下创建 Android 应用程序

javascript - 使用 Protractor 测试时如何找到 ng-repeater 的最后一个元素

node.js - 如何在所有测试之前设置 DynamoDB 表并在所有测试之后将其拆除?

ruby-on-rails - 测试(测试单元)元标记的名称和内容以确保内容不为空

javascript - Jest 找不到在我的测试中导入的组件