【发布时间】:2021-03-12 08:18:21
【问题描述】:
我有一个名为Auth.app_id 的函数,它首先尝试从应用程序的配置中读取app_id,如果丢失,将查找系统环境。
测试此类功能的最佳实践是什么?当然,事先在测试中使用Application.put_env 和System.put_env 是非常糟糕的做法,因为我们使用全局变量进行操作,并且不可能进行异步测试。
test "getting config variables" do
Application.put_env(:appname, :app_id, "123")
assert Auth.app_id === "123"
end
test "getting env variables" do
System.put_env("APPNAME_APP_ID", "111")
assert Auth.app_id === "111"
end
这是 getter 函数内部的样子:
def app_id do
Application.get_env(
:appname,
:app_id,
System.get_env("APPNAME_APP_ID")
)
end
问题是我有很多使用这些 getter 的函数,比如返回带有 app_id 作为参数的 url。
【问题讨论】:
-
我知道这是一个令人毛骨悚然的细节,但那些并不是真正的“吸气剂”。不是 OO 意义上的。事实上,您可以概括
app_id函数,方法是不隐藏其中的细节,而是将值作为参数进行检索。
标签: elixir